May 22, 2011

How to Enable or Disable ViewState Property in ASP.NET

ViewState:
ViewState allows the state of objects to be stored in a hidden field on the page. ViewState is transported to the client and back to the server, and is not stored on the server or any other external source. ViewState is used to retain the state of server-side objects between post backs.


Enable ViewState Property:
It allows the page to save the users input on a form across postbacks. It saves the server-side values for a given control into ViewState, which is stored as a hidden value on the page before sending the page to the clients browser


Show ViewState:



<%@ Page Language="C#" %>
<!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Transitional//EN" "http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd">

<script runat="server">    

    protected void btnAdd_Click(object sender, EventArgs e)

    {

        lblCounter.Text = (Int32.Parse(lblCounter.Text) + 1).ToString();

    }

</script>

<html xmlns="http://www.w3.org/1999/xhtml" >

<head id="Head1" runat="server">

    <title>Show View State</title>

</head>

<body>

    <form id="form1" runat="server">

    <div>    

    <asp:Button id="btnAdd" Text="Add" OnClick="btnAdd_Click" Runat="server" />    

    <asp:Label id="lblCounter" Text="0" Runat="server" />    

    </div>

    </form>

</body>

</html>


Output:




No comments:

Post a Comment