ASP.NET includes several State Management features. One of the feature is ViewState.
ViewState is used to preserve values of page and controls between the round trips or the postbacks.
It stores information of the specific page.
When the user submit the form in ASP.NET, the page reappears with the saved values. The values do not get cleared. This is because of ViewState.
Let the user submits the form, and server returns back with some error, the values in the form do not get cleared, rather all the filled values reappear.
We can set ViewState property of the controls. Let if the control binds via database so in every postback it will refresh which will increase the size of ViewState. So to avoid this, set the EnableViewState property of the particular control to False.
Pros and Cons:
Pros:
No time out takes place.
Can store any type of data.
Supports every browser.
Can store data between postbacks.
Cons:
Not suitable to store large amount of data.(If ViewState contains large amount of data, it would affect the performance of the page.)
No secure data can be stored.
Let we have an example:
<!DOCTYPE html>
<html>
<head runat="server">
<title></title>
</head>
<body>
<form id="form1" runat="server">
Place name: <asp:TextBox id="txtName" runat="server" />
<asp:Button ID="btnSubmit" Text="Submit" runat="server" onclick="btnSubmit" />
<p><asp:Label id="lblName" runat="server" /></p>
</form>
</body>
</html>
protected void btnSubmit(object sender, EventArgs e)
{
lblName.Text = "This is " + txtName.Text;
}
Output
0 Comment(s)