Wednesday, September 24, 2008

What is viewstate?

When we ceate a component like asp:textbox or asp:button in a web form, we can observe an attribute named "EnablViewState", which is boolean.

By default the view state of the component is true.
Usually we have view state and control state for a component inorder to provide page persistence during the post backs or between http requests.
In which we can disable or enable the view state of the component but cannot the control state.

So control state of the component is mandatory to provide minimun information to the user.
The reason behind introducing view state is to avert unnecessary data rendered into html, which increases performance.


Example :
in aspx page :
<form id="form1" runat="server">
<div>
<asp:Button ID="btnEF" Text="False" runat="server" OnClick="btnEF_Click" />
<asp:Button ID="btnTF" Text="True" runat="server" OnClick="btnTF_Click" />

<asp:TextBox ID="txtEF" Text="False" EnableViewState="false" runat="server"></asp:TextBox>
<asp:Button ID="btnTest" Text="Test" runat="server" EnableViewState="false" />
</div>
</form>


in aspx.cs page :

protected void btnEF_Click(object sender, EventArgs e)
{
txtEF.Text = "1";
btnTest.Text = "1";
}
protected void btnTF_Click(object sender, EventArgs e)
{
txtEF.Text = "2";
txtEF.Visible =false;
btnTest.Text = "2";
}

Observing the above example we can find 2 controls (textbox and button) with enable view state false in aspx.
In aspx.cs "btnEF_Click" we are just trying to assign text but not controlling the view of the controls.
but "btnTF_Click" we are assiging the text but controlling the visiblity of a text box control whose enable view state is false.
So in "btnTF_Click" we are setting the textbox control visibilty false, now when you click on button "btnEF" i.e; in "btnEF_Click" function we have not
written any code to set the component visibilty to true, but the text box component will be displayed because its enable view state is false whose view state is
not saved.

No comments: