What is ASP.NET State Management? How to manage state in ASP.NET?


In this article I am going to explain about overall what are the state management controls are used in ASP.NET. How to manage state across post back and across all other pages etc. with detailed example code.

Description :


State management is used to keep values across post back event occurs. There are two types of state management are available in the ASP.NET.

1) Client based State management

2) Server based State management



Client based state management


Here I am going to explain about in detail about client based state management.

1) What is View State?


View state is nothing but it is used to store the value across post back in the same page, Mean if you store the value in the Default.aspx page then that value is accessible only within the same Default.aspx page not able to call in the other pages like Default2.aspx etc.

Advantages:

  • Simple for a page level data

  • Possible to Encrypted

  • Can be set at the control level.

Disadvantage:

  • Overhead in encoding View State Values.

  • Makes a page heavy

View State Example


Client side

Enter Your Name <asp:TextBox ID="TextBox1" runat="server"></asp:TextBox><br />
<asp:Button ID="Button1" runat="server" Text="Submit" onclick="Button1_Click" /><br />
<asp:Label ID="lblmsg" runat="server"></asp:Label>

Code behind

protected void Button1_Click(object sender, EventArgs e)
{
//Declare value in the View State
ViewState["key"] = TextBox1.Text;

//check view state have value using if loop before assign value
if (ViewState["key"] != null && ViewState["key"].ToString() != "")
{
//Get value from view state like below
lblmsg.Text = ViewState["key"].ToString();
}

//Remove View state value like this
ViewState["key"] = null;
}

2) What is Hidden field?


Hidden file is also client based state management control. It is keep the value across post back Refer below code sample for that. Hidden fields are also used to store data at the page level.

Advantages:

  • Simple to implement for a page specific data.

  • Can store small amount of data so they take less size.

Disadvantage:

  • Inappropriate for sensitive data.

  • Hidden Field value can be intercepted (clearly Visible) when over the network.

Hidden Field Example


Client side

Enter Name
<asp:TextBox ID="TextBox1" runat="server"></asp:TextBox><br />
<asp:Button ID="Button1" runat="server" Text="Button" onclick="Button1_Click" /><br />
<asp:Label ID="lblmsg" runat="server"></asp:Label>
<asp:HiddenField ID="HiddenField1" runat="server" />

Code behind

protected void Button1_Click(object sender, EventArgs e)
{
//Assign value in hidden field like below
HiddenField1.Value = TextBox1.Text;

//Get the value from hidden field like below
lblmsg.Text = HiddenField1.Value;
}

3) What is Cookie?


A Cookie is a small piece of data stored on the user's computer. Most browsers allow only 20 cookies per site

Advantages:

  • Simplicity easy to create and use in web page.

Disadvantages

  • Cookies functionality may be disabled on Users Browsers, so make sure before using this.

  • Cookies are transmitted for each HTTP request/response causing over head on bandwidth.

  • Cookies are Inappropriate for sensitive data like banking applications etc.

Cookie Example



protected void Button1_Click(object sender, EventArgs e)
{
//Add cookies with key and name in the user's browsers
Response.Cookies["UserId"].Value = TextBox1.Text;

//Get back value from cookies and assign in the label control
lblmsg.Text = Request.Cookies["UserId"].Value.ToString();
}

4) What is Query string?


Query String is usually used to send information from one page to another page. They are passed along with URL in clear text and also encrypted text passed through url.

Advantages:

  • Simple for to implement.

Disadvantage:

  • Human Readable unless you are not encrypt text before passing to query string.

  • Client Browser limit on URL length.

  • Cross paging functionality makes it redundant.

  • Easily modified by end user at run time if query string not encrypt.

Query String Example


Example


Page1.aspx Client side

Enter Name
<asp:TextBox ID="TextBox1" runat="server"></asp:TextBox><br />
<asp:Button ID="Button1" runat="server" Text="Button" OnClick="Button1_Click" /><br />

Page1.aspx.cs Code behind

protected void Button1_Click(object sender, EventArgs e)
{
//Get the text box value and pass that value in to other page using query string
Response.Redirect("04QryString2.aspx?name=" + TextBox1.Text);
}

Page2.aspx.cs

In the second page get that query string value and bind in the label like below

protected void Page_Load(object sender, EventArgs e)
{
if (!Page.IsPostBack)
{
Label1.Text = Request.QueryString["name"].ToString();
}
}



Server based state management


Here I am going to explain about in detail about server based state management. Here all this values are store in the server not in user client side.

1) What is Session?


Session is used to keep values across post back and keep values across all pages too, mean if you declare value in the session variable you can call that session value in any page of the project. Compare to other View state, hidden Field etc. Session have most popular state management control.

Session Example


Page1.aspx Client side

Enter Name
<asp:TextBox ID="TextBox1" runat="server"></asp:TextBox><br />
<asp:Button ID="Button1" runat="server" Text="Button" OnClick="Button1_Click" /><br />

Page1.aspx.cs Code Behind

protected void Button1_Click(object sender, EventArgs e)
{
//initialize session value like below
Session["name"] = TextBox1.Text;
Response.Redirect("05Session2.aspx");
}

Page2.aspx Client side

<asp:Label ID="lblmsg" runat="server" Text="Label"></asp:Label>


Page2.aspx.cs Code Behind

protected void Page_Load(object sender, EventArgs e)
{
if (!Page.IsPostBack)
{
//Check before bind session have value
if (Session["name"] != null)
{
lblmsg.Text = Session["name"].ToString();
}

//Remove particular session and its value
Session.Remove("name");

//Remove all session in the project like below
Session.RemoveAll();
}
}

2) What is Cache?


Cache is also used to keep values in the server. It is not like session, it is application oriented control.

Cache Example


Code behind

protected void Button1_Click(object sender, EventArgs e)
{
//Create cache like below
Cache["t1"] = TextBox1.Text;

//Get value from cache below
Label1.Text = Cache["t1"].ToString();

//Remove cache and its value like below
Cache.Remove("t1");

}



Source code:

I have covered all state management control examples in the source folder download it and test it.

Client Side: ASP.NET
Code Behind: C#

Conclusion

I hope this article is help you to know overall what are the most familiar state management technique used in the ASPNET.


Attachments

  • stateManagement_ASP.NET (44056-02044-stateManagement-ASP.NET.rar)
  • Comments

    Author: Sridhar Thota30 Jun 2015 Member Level: Gold   Points : 8

    server side state management:
    Application state:
    1.The application state is maintained in the
    application level. It is common for all users in a
    application.
    2.Application variable can be set as
    Application[ "Countvariable" ] = Convert.ToInt
    32(Application[ "Countvariable" ]) + 1;
    lbl.text= Application[ "Countvariable" ].ToString();
    3.Some application events in global.asax are
    Application_start
    void Application_Start( object sender, EventArgs
    e)
    {
    Application[ "Countvariable" ] = 0;
    }
    Application_Error.
    Application_End.

    Session state:
    1.Session state is maintained user level. It is
    different for different users.
    2.Session variable can be set as
    Session[ "Countvariable" ] = Convert.ToInt
    32(Session["Countvariable" ]) + 1;
    lbl.text=Session["Countvariable"].ToString();
    3.Some session events in global.asax are
    Session_Start
    void Session_Start( object sender, EventArgs e)
    {
    Session[ "Count" ] = 0;
    }
    Session_End

    There are different session modes
    1.Inproc Session:
    Session maintained in the website process is
    called Inproc Session.
    Restarting website will erase the session.
    2.State server session:
    Session maintained out side the website in the
    state server is called state server session.
    Restarting state server will erase the session.
    3.Sql server session:
    Session maintained out side the website in the
    Sql server database is called sql server session.
    Session is maintained until we delete from the
    database table.

    Regards

    Sridhar Thota.
    DNS Member.
    "Hope for the best.. prepare for the worst.."



  • Do not include your name, "with regards" etc in the comment. Write detailed comment, relevant to the topic.
  • No HTML formatting and links to other web sites are allowed.
  • This is a strictly moderated site. Absolutely no spam allowed.
  • Name:
    Email: