How are class fields treated in an ASP.NET web form class?
Consider a web form (aspx) wth an associated codefile (aspx.cs).
In the codefile, for instance, we have the following:
public partial class MyPage : System.Web.UI.Page {
int myint;
string mystring;
public void Page_Load(object sender, EventArgs e) {
...
if (!this.IsPostBack) {
this.myint = 2;
this.mystring = "Hello";
}
...
}
}
Can I expect to have the two variables everyti开发者_运维问答me the page is posted back? I mean: are page class fields kept as part of the web form state?
Thankyou
No, these objects would be disposed at the end of the Page-Lifecycle. If you want to persist them in ViewState you have to add them to it.
Objects that need to be stored in ViewState must be serializable.
Storing Simple Data Types in the ViewState
Like most types of state management in ASP.NET, view state relies on a dictionary collection, where each item is indexed with a unique string name. For example, consider this code:
ViewState["ViewStateVariableName"] = 1;
This places the value 1 (or rather, an integer that contains the value 1) into the ViewState collection and gives it the descriptive name ViewStateVariable. If there is currently no item with the name ViewStateVariable, a new item will be added automatically. If there is already an item indexed under this name, it will be replaced.
You can access this variable anywhere within the page/control where the viewstate variable has been added. When retrieving a value, you use the key name.
int number = (int) ViewState["ViewStateVariable"];
You also need to cast the retrieved value to the appropriate data type. This is because the ViewState collection stores all items as generic objects which also give you the flexibility to store any type of basic data types in it. In fact, you can even store your custom objects in the view state.
Storing Objects in View State
You can store your own objects in view state just as easily as you store numeric and string types. However, to store an item in view state, ASP.NET must be able to convert it into a stream of bytes so that it can be added to the hidden input field in the page. This process is called serialization. If your objects aren't serializable (and by default they aren't), you'll receive an error message when you attempt to place them in view state.
- http://www.beansoftware.com/ASP.NET-Tutorials/ViewState-In-ASP.NET.aspx
- http://msdn.microsoft.com/en-us/magazine/cc188774.aspx
No, they are not. They are not persisted to viewstate.
In order to persist them, you need to make them properties that store their values in ViewState, like so:
public string MyString
{
get { return (string) ViewState["MyString"];
set { ViewState["MyString"] = value; }
}
精彩评论