ASP.NET State Management

State management is very important and useful in ASP.NET. It is also asked in many interviews with fresher and more experienced developers.

ASP.NET State management preserves state control and objects in an application because ASP.NET web applications are stateless. A new instance of the Web page class is created each time the page is posted to the server. If a user enters information into a web application, that information would be lost in the round trip from the browser (MSDN).

In a single line, State management maintains and stores the information of any user till the end of the user session.

Two types of State Management techniques are available in ASP.NET as in the following figure.

State Management

Figure 1: State Management Part

Server-side
 

Session

The session is a very important technique to maintain state. Normally session is used to store information and identity. The server stores information using Sessionid.

Set User Session

protected void btnSubmit_Click(object sender, EventArgs e)
{
    Session["UserName"] = txtName.Text;

    Response.Redirect("Home.aspx");
}

Session Event

The session event can be seen in the project Global.asax file.

Two types of Session Events

Session_Start

The Session_start event is raised every time a new user requests without a session ID.

void Session_Start(object sender, EventArgs e)
{
    Session["master"] = "~/Master.master";
}

Session_End

The Session_End event is raised when the session is ended by a user or a time out using the Session end method.

void Session_End(object sender, EventArgs e)
{
    Response.Write("Session_End");
}

The session is stored in the following ways in ASP.NET.

  • InProcMode: It is a default session mode and a value stored in web server memory (IIS). In this, the session value is stored with server start and it ends when the server is restarted.
  • State Server Mode: In this mode session data is stored in a separate server.
  • SQL Server Mode: This session is stored in the database. It is a secure mode.
  • Custom Mode: Generally under session data is stored in InProc, SQL Server, State server, etc. If you store session data with other new techniques then provide ASP.NET.

Application

The application State is a server-side management state. It is also called application-level state management. This mainly stores user activity in server memory and application events shown in Global.asax file.

There are three types of applications in ASP.NET.

Application_Start

This event begins with domain start.

void Application_Start(object sender, EventArgs e)
{
    Application["AppstartMessage"] = "Welcome to CSharp Corner Developer Community";
}

Application_Error

In this section manage unhandled exception errors.

void Application_Error(object sender, EventArgs e)
{
    // Write an unhandled error code exception
}

Application_ End

This ends with domain or restarts IIS.

void Application_End(object sender, EventArgs e)
{
    Application["AppEndMessage"] = "Application Closed";
}

Cache

The cache is stored on the server side. It implements Page Caching and data caching. The cache is used to set expiration policies.

Response.Cache.SetExpiresTime(DateTime.Now.AddDays(1));

Client Side

Now here I am explaining client-side state management one by one:

Also, state management has the following four important parts available on the client side.

Cookie

Cookie is a small and an important part of ASP.NET. In this store user information, sessions, and applications. It can be created constantly and temporarily and they work with browser requests. Cookies are stored on the client side. The server can read cookies and abstract data.

Two types of cookies are available.

Persistence

This type of cookie works with Date and time.

Response.Cookies["CookieName"].Value = "Test Cookies";
// Set expire time
Response.Cookies["CookieName"].Expires = DateTime.Today.AddHours(1);

Non-Persistence

This is a temporary cookie. It is created with an access application and discards the closed application.

Response.Cookies["CookieName"].Value = "TestCookies";

Control state

The control state technique is developed to maintain data work properly in order. We can use view state but suppose view state is disabled by the user, the control will not work as expected. For the expected results of the control, we have to use the Control State. In the application, the Viewstate is by default true. Sometimes we need to use custom control to manage applications properly.

if (!IsPostBack)
{
    lblmsg1.Text = "Welcome to C# corner";
    lblmsg2.Text = "Welcome to C# corner community";
}

When two messages are displayed on a Postback event, then control which one is displayed by using a customized control state.

Hidden Field

Hidden fields are used to store value on the client side. The hidden field is not displayed on the browser, but it works on a request.

if (HiddenField1.Value != null)
{
    int val = Convert.ToInt32(HiddenField1.Value) + 1;
    HiddenField1.Value = val.ToString();
    Label1.Text = val.ToString();
}

ViewState

ViewState is a very useful client-side property. It is used for page-level state management. Viewstate stores any type of data and is used for sending and receiving information.

Example 1 -Count.

ViewState Demo Count: <asp:Label runat="server" id="lblcount" />
<asp:Button runat="server" id="Submit" onclick="Submit_Click" text="show" />

protected void Page_Load(object sender, EventArgs e)
{
    if (IsPostBack)
    {
        if (ViewState["count"] != null)
        {
            int ViewstateVal = Convert.ToInt32(ViewState["count"]) + 1;
            lblcount.Text = ViewstateVal.ToString();
            ViewState["count"] = ViewstateVal.ToString();
        }
        else
        {
            ViewState["count"] = "1";
        }
    }
}

protected void Submit_Click(object sender, EventArgs e)
{
    lblcount.Text = ViewState["count"].ToString();
}

Example 2 -Set/Get user.

if (ViewState["UserName"] != null)
    lblName.Text = ViewState["UserName"].ToString();

OR,

ViewState["UserName"] = txtUserName.Text;

Viewstate is easy to apply and does not need access to any server resources. In a Viewstate, do not store big data, only store small values. Viewstate enables and disables page-level control. It also supports Encryption and Decryption and data/value is stored in hashed format. So we are not storing important data such as passwords, account information, etc. When more data is stored in this, then the page becomes heavy.

Query String

The query string stores the value in the URL.

Response.Redirect("ShowStringValue.aspx?Username=" + txtUsername.Text);

It is visible to all the users in the URL as in the following link.

URL

I hope you enjoyed the clear state management concept in ASP.NET.

Here is one more detailed tutorial, ASP.NET State Management Tutorial


Similar Articles