从C#类访问ASP.NET页的TextBox值 [英] Access TextBox value of an ASP.NET page from C# class
问题描述
假设ASP.NET页上有一个TextBox
Say there is a TextBox on an ASP.NET page
<asp:TextBox id="DateTextBox" runat="server" />
在代码的后面设置了一些值.
with some value set in the code-behind.
如何通过HttpContext或其他方式从另一类C#代码文件访问该值?
How to access that value from another class of C# code-file through HttpContext or any other way?
推荐答案
即使是静态方法,也可以通过HttpContext
访问页面中的属性.
You can access a property in you page via HttpContext
even from a static method.
在您的页面中:
public string DateTextBoxText
{
get{ return this.DateTextBox.Text; }
set{ this.DateTextBox.Text = value; }
}
其他地方(即使在其他dll中):
somewhere else(even in a different dll):
public class Data
{
public static string GetData()
{
TypeOfYourPage page = HttpContext.Current.Handler as TypeOfYourPage;
if (page != null)
{
return page.DateTextBoxText;
//btw, what a strange method!
}
return null;
}
}
请注意,只有在此页面的生命周期内调用此方法时,此方法才有效.
Note that this works only if it's called from within a lifecycle of this page.
通常最好使用ViewState
或Session
在回发期间维护变量.或者,当您引用此页面时,直接使用上面的属性即可.
It's normally better to use ViewState
or Session
to maintain variables across postback. Or just use the property above directly when you have a reference to this page.
这篇关于从C#类访问ASP.NET页的TextBox值的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!