Http protocol is stateless. So maintaining state between post-backs by the user is very difficult. The asp.net framework provides state management technique to maintain state between post-backs.
What is state management?
State management means to preserve the state of a control, web page etc.HTTP is a stateless protocol by nature. So, State management is a mechanism to preserve state (i.e. state of a webpage, a control or an object etc.) between subsequent requests to server from one or more clients.
Asp.Net provides two types of state management, client side, and server side.
Client Side
Client-side state management technique stores information on the client side like the browser or client computer. The benefit of the client side is to reduce the burden of the server to store state information.
These are the types of Client-side state management
- View State
- Hidden field
- Cookies
- Query Strings
- Control State
Server Side
Server side state management technique stores information on the server side.
- Application State
- Session State
- Profile properties
Query String
Query string is client-side state management variable. This is very easy to use. Basically, we are using the query string to send the small amount of text from one page to another with help of page URL. Just after page url, you have to add ? sign and after that add your query string key and value. Whatever data you send through query string that visible to everyone.
Below codes is redirecting to the Default4.aspx page and added a query string “Name” that value is Amit.
// Use Query String to send Name to next page
Response.Redirect("Default4.aspx?Name=qawithexperts");
On Default4.aspx, first, check that query string is available or not. If available then retrieve that query string value using query string name.
// Retrieve Query String Value
if (Request.QueryString["Name"] != null)
{
string name = Request.QueryString["Name"].ToString();
}
Encoded Query String
We learn that query string is very easy to use but apart from using it have some disadvantage that query string cannot accept Space and & characters. When you send space in query string you will see in url that space is replaced to %20 and whenever you send any query string that value contains & character then while retrieving it show only that text that comes before & sign. For example, if you are sending query string Name that value is Tom&Jerry then on other side it will retrieve as Tom only.
// Send Query String
Response.Redirect("Default4.aspx?Name=" + Server.UrlEncode(txtName.Text) +
"&City=" + Server.UrlEncode(txtCity.Text));
Hidden Fields
Hidden field is very simple control to store small amount of data. It is a asp.net tool that present on web page. You can store data in hidden field from page side or C# page side. benefits of hidden field is that it never lost stored values during post backs.
<asp:HiddenField ID="HiddenField1" runat="server" />
Store data in hidden field
// Use Hidden Field to store Name
HiddenField1.Value = "qawithexperts";
Retrieve stored data from hidden field.
// Retrieve Hidden Field value
string name = HiddenField1.Value;
Cookies
Cookies are used to store small amount of data. Best example of cookies is to store login userid
You can create a new cookie by using Response.Cookies that contains collection of cookies which is sent from web server to web browser.
Creating Cookie
// Creating a Cookies
Response.Cookies["user"].Value = "Pika";
You can retrieve cookies values by their name, but remember that before retrieving cookies value, first check that cookies is exists or not otherwise it will throw an exception like : System.NullReferenceException: Object reference not set to an instance of an object.
Reading Cookies
// Reading Cookies Value
if (Request.Cookies["user"] != null)
{
string name = Request.Cookies["user"].Value;
Response.Write("Cookies Value - " + name);
}
Persistent Cookies
Cookies name is case sensitive. When you will close the browser then cookies lost their values. If you want to create cookies that containing values to the specified date no matter how many time browser is closed, on that time need to create persistent cookies that contain expiry date of cookies.
// Creating Persistent Cookies
Response.Cookies["user"].Value = "Pika";
Response.Cookies["user"].Expires = DateTime.Now.AddDays(10);
View State
View state is a client side state management mechanism. View state does not stored data on server side. Once you stored data in view state then you can retrieve that data from anywhere on the page.
Creating View State
Storing data in view state is very easy. You can store data in view state by assigning a key that will use to retrieve view state stored data. Below codes are showing to storing data in view state.
// Use ViewState to store Name
ViewState["Name"] = "qawithexperts";
Reading View State
Below codes are showing that retrieving data from view state. While retrieving you have to cast data type.
// Retrieve ViewState value
if (ViewState["Name"] != null)
{
string name = ViewState["Name"].ToString();
}
View State Encryption
When you stored data into view state then internally its store into a html hidden field. View state stores data in hidden field as hashed base64 encoded string format. Hidden field hashed string can easily decoded. So its security risk that someone can change or modify that data if data is highly sensitive. To overcome these problems use view state EnableViewStateMac or viewStateEncryptionMode property.
- Using EnableViewStateMac
- Use viewStateEncryptionMode
Disadvantage of View State
- Performance issues
- Security concern
Control State
View state use to preserve page and page control values between round trips of the page. But, if view state disable for the page, then view state of the page controls is not maintained. So overcome this problem use control state that cannot be disabled. Control state can store control state. By default, the Asp.Net framework stores control state in the page hidden field same as view state.
On post back, Asp.Net deserializes the content of hidden field and loads state into each control that is registered for control state.
You can implement control state by overriding following methods of the base class:
- OnInit - that contains two methods:
- Page.RegisterRequiresControlState(this)
- b. base.OnInit(e)
- SaveControlState
- LoadControlState
Session State
Session State is one of the important state management variables in Asp.Net. It’s working on the server side. The advantage of session state is that once you store your data in session and access that data from anywhere in the application across multiple pages. The advantage of session state over cookies is that session can store any type of data as well as complete dataset whereas cookies can store only small amount of data.
Create Session
A new session can be created by specifying session name in the session variable. For example, in below code we are creating a new session that name is UserName. In this session, we are storing simply a string value Asphelps. You can store any type of object data in session state.
Session["UserName"] = "qawithexperts";
Read Session
Once you created session then, you can retrieve stored object in session from anywhere in the application. Use below code to retrieve your session data from any page in the application.
if (Session["UserName"] != null)
{
string userName = Session["UserName"].ToString();
}
End Session
You can stop user session any time in the application. You have three option to stop user session.
- Abandon - End user session in the application.
- Remove - Remove a particular session in the application.
- Clear - Clear all session object.
// Remove UserName session
Session.Remove("UserName");
// End a user session
Session.Abandon();
// Clear all session items
Session.Clear();
Control Session Timeout
When you are using session then session will expire after specific time. This time is known as session timeout. Default session timeout value is 20 minutes. But you can increase session timeout using session's TimeOut propery by declaring on page or in Web.Config.
<system.web>
<sessionState timeout="60" />
</system.web>
Application State
Application state is server-side state management variable. Application state stored data in memory on the server. Application state is global storage mechanism that access by all the page by all user and sessions. It is very useful to store small amounts of data that is common for all users. Application state lost their stored values when exception occurred or application restarted.
// Create Application State
Application["AppName"] = "qawithexperts";
Retrieve stored value from application state.
// Retrieving value from Application State
string name = Application["AppName"].ToString();
Profile Properties:
- The ASP.NET profile feature associates information with an individual user and stores the information in a persistent format.
- Profiles allow you to manage user information without requiring you to create and maintain your own database
- The ASP.NET profile feature makes the user information available using a strongly typed API that you can access from anywhere in your application.
- To use profiles, you first enable profiles by modifying the configuration file for your ASP.NET Web application