What is view state?
View State is one of the most important and useful client side state management mechanism. It can store the page value at the time of post back (Sending and Receiving information from Server) of your page. ASP.NET pages provide the ViewState property as a built-in structure for automatically storing values between multiple requests for the same page.
Example:
If you want to add one variable in View State,
ViewState["Var"]=Count;
For Retrieving information from View State
string Test=ViewState["TestVal"];
When we should use view state?
- Size of data should be small , because data are bind with page controls , so for larger amount of data it can be cause of performance overhead.
- Try to avoid storing secure data in view state
View State
use
Hidden
field to
store its information in a encoding format.
Suppose you
have written a simple code , to store a value of control:
ViewState["Value"] = MyControl.Text;
Now, Run you application, In Browser,
RighClick
> View
Source
, You will get the following section of code
How to store object in view state?
We can store an object easily as we can store string or integer type variable. But what we need ? we need to convert it into stream of byte. because as I already said , view state store information in hidden filed in the page. So we need to use Serialization. If object which we are trying to store in view state ,are not serializable , then we will get a error message .
Just take as example,
//Create a simple class and make it as
Serializable
[Serializable]
public class student
{
public int Roll;
public string Name;
public void AddStudent(int intRoll,int strName)
{
this.Roll=intRoll;
this.Name=strName;
}
}
Now we will try to store object of "
Student
" Class in a view state.//Store Student Class in View State
student _objStudent = new student();
_objStudent.AddStudent(2, "Abhijit");
ViewState["StudentObject"] = _objStudent;
//Retrieve Student information view state
student _objStudent;
_objStudent = (student)ViewState["StudentObject"];
Enabling and Disabling View State
You can enable and disable View state for a single control as well as at page level also. To turnoff view state for a single control , set EnableViewState Property of that control to false. e.g.:
TextBox1.EnableViewState =false;
To turnoff the view state of entire page, we need to set
EnableViewState
to false of Page Directive as shown bellow.
0 comments:
Post a Comment