X



Home>Tutorial>

ASP.Net State Management:All You Need To Know

Nuelson Penuel Friday, August 28, 2020 ASP.Net

Summary

In this post, I have explained asp.net state management in detail, give types of State management and code examples

ASP.Net State Management

State management in asp.net is used to preserve control and object state in asp.net application because asp.net runs in a standard protocol called HTTP and HTTP is stateless in other words web applications developed using asp.net are stateless. Each time a postback occurred on a page either through reloading or click action, a round trip will be make to the server and a new instance of the web page class is created and at this time, information will be lost. Without state management, any information entered by web application users would be lost in the round trip from the browser to the server. Hence, the reason why state management was introduced into asp.net by Microsoft is to maintain and store the information of any user till the end of the user's session.

Levels of State Management

1. Control level: by default controls provide state management automatically in ASP.NET. 2. Variable or object level: Member variables at page level are stateless and thus we need to maintain the state of member variables explicitly in ASP.NET. 3. Single or multiple page level: managing state between page requests i.e. multiple page levels as well as single page level. 4. User level: managing state as long as a user is running the application. 5. Application level: State Management for complete application irrespective of the user and it should be available to all users. 6. Application to application level: managing State between or among two or more applications.

Types of State Management

We have client side and server side state management. In asp.net, these client and server state management are further classified into 8 techniques to maintain data storage exists such as QueryString, Viewstate, Cookies, Control State, Hidden Field which are categorized as client side technique. ASP.Net also uses Sessions, Application State and Cache which are classified as server side technique.

Client Side State Management

In client side state management, information is always store on client system instead of the server. Client state management seems to be more better to an extent since information that have to be stored on the server which at the end leverage server cost. However, it also has its own drawbacks in the sense that information stored on the client side cannot be accessed aside the client system unless they are posted to server. State management has five important important techniques used for data management on the client side. These techniques are listed and explained below;

Query String

This technique happens to be the most light weight of all the state management because it doesn't add anything to your html document neither does it increase the size of the page. Everything is passed to the broswer's url. Query string has three major advantages that makes it popularly used which are; 1. Easy to use 2. Supported by all ancient and modern browsers 3. Not much effort is needed for using it if the information are not sensitive. But query string has its own disadvantages that makes it not that effective for data management such as; 1. Browsers restrict it not to carry more 255 characters 2. The information is always visible to anyone that have access to the system why the application is running. So encryption must be done on query string information if they are sensitive. A typical example of query string is below;
https://www.emmason247.com.ng/user-profile?id=095& email=myemail@domain.com
Query string can be declared at codebehind and only when a redirect is about to happen. For instance, here is a typical declaration of query string is; Place this code on the login click event
Response.Redirect("dashboard.aspx?cid=" & cid)
In the above example, cid is the client ID, and when a user enter his or her login details, after authentication the user unique ID is now passed to the broswer's url as query string. With this query string, if you want to make subsequent check of the user information via the user ID, it becomes so easy and quick. But note, do not pass user ID to broswer as query string without encryption. Now that we have passed the client ID as query string, let us see how we can get the client ID from the query string. If you notice, if we want to pass query string, we make use of Response, then if you want to get this value; you make use of Request.
Sub GetValue()
Dim cid As String
If Not Request.QueryString("cid") Is  Nothing Then
cid = Request.QueryString("cid")

End If
End Sub
See more about Query String here

ViewState

View state is known as a page-level state management technique. When you create new web application in visual studio, view State is turned on by default and normally serializes the data in every control on the page regardless of whether it is actually used during a post-back. Furthermore, viewstate is a very useful client side property as it stores any type of data and also used for sending and receiving information. View state can be used in different ways such as storing user ID and password though not advisable. It can also be used for keeping count of your page load so on and so forth. Below is a typical example of View State demonstration for persisting page count. Check this for full details on ASP.Net viewstate. In the this example, we are counting the number of postback caused by user interaction by clicking on button or link.
Protected Sub Page_Load(ByVal sender As Object, ByVal e As EventArgs)
    If Page.IsPostBack Then

        If Not ViewState("keepCount") Is Nothing Then
            Dim count As Integer 
 count = Convert.ToInt32(ViewState("keepCount")) + 1
            lblcount.Text = count
            ViewState("keepCount") = count
        Else
            ViewState("keepCount") = "1"
        End If
    End If
End Sub
From the above ViewState example, you can see that ViewState is easy to use and apply and perhaps, does not need access to any server resources. Caution: Never you store large data in ViewState, only store small values. When more data is stored in ViewState, then the page becomes heavy.

Cookies

Cookies is one of the ways that web developers used to store temporary information on the client side through the broswer's help. I said temporary data cos if you use it to permanent data then you are taking risk because once the user clear his or her broswer's Cookie files then your information stored will be gone In other words, cookie is a small piece of data stored on the user's computer by the web browser while browsing a website. Cookies were designed to be a reliable mechanism for websites to remember stateful information or to record the user's browsing activity. There are two types of cookies which are persistent cookie and non-persistent cookie.

Persistence Cookies

These are created with specific date or time for it to expire. Or better still permanently until clear by user. You can check my post on cookies for more understanding

Sub CreatePersistentCookie()
Dim cookieEx As New HttpCookie("username")
cookieEx.Value.Add = "Guru"

cookieEx.Expires = Date.Now.Adds(7) 'cookies that expires in 7 days
Response.Cookies.Add(cookieEx)

Non-persistence Cookies

While non-persistence cookies or in-memory cookies are temporary cookies

Sub CreateNonPersistentCookie()
Dim cookieEx As New HttpCookie("username")
cookieEx.Value.Add = "Guru"
Response.Cookies.Add(cookieEx)

To learn how to read and destroy cookies values, check more about cookies here

Control State

Control state is another state management technique used to maintain controls information. Though ViewState can be used to maintain controls management information, the control will not be able to work as expected if ViewState is disabled by user. So if you want the control to work as expected then you have to use Control State.

HiddenFields

Hidden field is another state management technique used for storing data on client side. As the name implies, hidden field is never showed to user or display on broswer but it works on a request. However, it is not advisable to use hidden field to store user information like password, username, credit cards details e.t.c cos anyone can see hidden field value when the page html source is view. A typical example of hidden field is

<asp:HiddenFieldID="HiddenField1" runat="server" />  

To append a value to hidden field is as simple as abc. Let us demonstrate a simple example

HiddenField1.Value = "This example of hidden field"

Now that you and I have known how to set hidden field value, it will also be important to know how to retrieve the appended values. To get hidden field value, is also as simple as abc. Let us take a simple demonstration. In the example below, we are going to display the value of the hidden field using message box and label

Script manager.RegisterStartupScript(Page, Page.GetType(),"my key", "alert (" + HiddenField1.Value + ");", True)

'Just use label
Label1.Text =HiddenField1.Value

See more about hidden field here

Server Side State Management

Session

Session is a server side state management technique used to store data on server side. Normally session is used to store information and identity. The server stores information using Sessionid. Information stored using sessions are not visible to users but that doesn't mean that the information can't be retrieve by hackers. So you are advised to encrypt any information you intend to store in session state. To store information in session, is easy with just one line of code;
Session ("username") = "guru"
And to retrieve information from session, you have to first check if the session exists or not else you will receive error.
If Not Session("username") Is Nothing Then

Label1.Text = Session ("username") 

    Else

'code to execute

End If

Application State

Application state in asp.net is a server side state management technique. The information stored in application state can be used by all users of that particular application and can be accessed anywhere in the application. Application state management is also known as application level state management. This technique was provided via the HttpApplicationState class as a way of storing application specific information globally and makes the information to be visible. Application state plays a very important role mostly when you want to keep count of page visitors. You can count how many times a given page has been visited through the use of application state. When using application state management, be sure to use Application.Lock() and Application.Unlock() else the result will not be accurate. Below is a simple code that can help you to count page visitors accurately on page load event.
Protected Sub Page_Load(ByVal sender As Object, ByVal e As System.EventArgs) Handles Me.Load
Application.Lock()
Dim res As Integer = 0
If Not Application("count") Is Nothing Then            
res = Convert.ToInt32(Application("count"))
End If        
res += 1      
Application("count") = res     Application.UnLock() 
Label1.Text = "This page has been visited " & res &  " times"   
End Sub
If you run the application, you will see that the page visit count will be increasing. There are three types of application state but will not be cover here. See more about application state here;

Cache

Cache is used when your site files such as CSS, images, javascript doesn't change frequently but are always needed by the application users. Examples of files that can be cache are style sheet, javascript and static images e.t.c Cache is stored on server side. It implements Page Caching and data caching. Cache is use to set expiration polices Response.Cache.SetExpiresTime(DateTime.Now.AddDays(1)); More about caching here

| | Views(493)

See Demo | Download File


Add your comment. Indicate code using code tag


Words: 0 | Chars: 0 | Reading Duration: 0



Images Attachment




Emmason Integratded Services(2017-2024)
All Rights Reserved
Designed and Maintained By Emmason Integrated Services