问题
Say there is a TextBox on an ASP.NET page
<asp:TextBox id="DateTextBox" runat="server" />
with some value set in the code-behind.
How to access that value from another class of C# code-file through HttpContext or any other way?
回答1:
You can access a property in you page via HttpContext
even from a static method.
in your page:
public string DateTextBoxText
{
get{ return this.DateTextBox.Text; }
set{ this.DateTextBox.Text = value; }
}
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.
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.
回答2:
You can create a public property
within the control that returns a reference to the textbox.
You can then use this property to reference the textbox.
OR
You can store in into session
and then access it in your entire application.
回答3:
Store it in the HttpContext Session
http://www.codeproject.com/Articles/32545/Exploring-Session-in-ASP-Net
//Storing UserName in Session
Session["DateTextBox"] = DateTextBox.Text;
Now, let's see how we can retrieve values from session:
//Check weather session variable null or not
if (Session["DateTextBox"] != null)
{
// use it...
}
回答4:
You could place the value in the Session during the post back. Then access it from the Session in the other class. So in your form load event write this:
Session["MyValue"] = DateTextBox.Text
and then in the other class write this:
var val = HttpContext.Current.Session["MyValue"];
来源:https://stackoverflow.com/questions/15450158/access-textbox-value-of-an-asp-net-page-from-c-sharp-class