Monday, November 14, 2016

State Management in asp.net- Part 2


View State: 

It is one of client side state management technique.

When a user sends a request to server and response came back to the user then we need to maintain the data send by the user. In view state, state information is maintained in the page level. In the page state information is stored in the hidden field. In the hidden field value is stored in the form of hashed string. In case the length of hash string exceed by some fixed length then another hidden field is created and so on. Programmatically it uses the “Dictionary Object” i.e. key and value pair to store the data in view state.

By using view state we can maintain the page data when user sends the request of same page multiple times. Means we can maintain the data of a page till that page is active.

Asp.net maintains the state information of the asp.net controls and page by default.

Here let us see the example of storing information in view state and retrieving it back:

Default.aspx:

<%@ Page Language="C#" AutoEventWireup="true" CodeFile="Default.aspx.cs" Inherits="_Default" EnableEventValidation="false" %>

<!DOCTYPE html>

<html xmlns="http://www.w3.org/1999/xhtml">
<head runat="server">
    <title></title>
</head>
<body>
    <form id="form1" runat="server">
    <div>
    Hello!!! this is home page
        <asp:TextBox ID="txtName" runat="server"></asp:TextBox>
        <asp:Button ID="btn" Text="Submit" runat="server" OnClick="btn_Click"/>
        <asp:Label ID="lbl" runat="server" BackColor="Yellow"></asp:Label>
        <asp:Label ID="lbl2" runat="server"></asp:Label>
    </div>
    </form>
</body>
</html>


Default.aspx.cs:

using System;

public partial class _Default : System.Web.UI.Page
{
    string name = "abc";
    protected void Page_Load(object sender, EventArgs e)
    {

        lbl.Text = name;

        if (ViewState["Name"] != null)
        lbl2.Text = ViewState["Name"].ToString(); // Getting stored information from          //view state
    }

    protected void btn_Click(object sender, EventArgs e)
    {
        ViewState["Name"] = name + txtName.Text; //Storing information in view state
        name = name + txtName.Text;
    }
}


    1.       Enter the value in textbox and click the submit button. It will store the “value stored in the name variable + value entered into the textbox”.

    2.       Again click on “Submit” button.

    3.       See the value of “ViewState["Name"]”. Also check the value stored into the “name” variable.