Hypertext Transfer Protocol (HTTP) is a stateless protocol. When the client disconnects from the server, the ASP.NET engine discards the page object. This way, each web application can scale to serve a large number of requests simultaneously without exhausting server memory.
However, some technique is needed to store the information between requests and retrieve it when needed. This information is called state, which is the current values of all controls and variables used by the current user in the current session.
ASP.NET manages four states:
view state
control state
session state
Application status
View state is the state of the page and all its controls. It remains unchanged through the ASP.NET framework's feedback.
When a page is sent back to the client, the properties and controls of these page changes are determined and stored in the value of a hidden input field named _VIEWSTATE. When the page is posted back again, the _VIEWSTATE field is sent to the server with the HTTP request.
View state can be enabled or disabled for:
Whole application : Set the EnableViewState property of the section in the web.config file.
A page : Set the EnableViewState property of the page command to <%@ Page Language="C#" EnableViewState="false" %>
A control : Set the control.EnableViewState property.
It does this by using a view state object, which is defined by a StateBag class defined by a set of view state items. The StateBag is a data structure that contains property value pairs and is stored as a string associated with an object.
The StateBag class has the following properties:
property | describe |
---|---|
Item(name) | The value of the view state with the specified name, which is the default property of the StateBag. |
Count | The name of the item in the status collection. |
Keys | A collection of keys for all items in the collection. |
Values | The collection of values for all items in the collection. |
The StateBag class has the following methods:
method | describe |
---|---|
Add(name, value) | Adds an item to the viewstate collection, updating existing items. |
Clear | Removes all items from the collection. |
Equals(Object) | Determines whether the specified object is equal to the current object. |
Finalize | Allows resources to be released and other cleanup operations to be performed. |
GetEnumerator | Returns a counter of key/value pairs for duplicate StateItem objects stored in the StateBag object. |
GetType | Get the type of the current instance. |
IsItemDirty | Check the object stored in the StateBag to confirm whether it has been modified. |
Remove(name) | Remove custom items. |
SetDirty | Sets the state of the StateBag object and the Dirty property of each contained StateItem object. |
SetItemDirty | Sets the Dirty property for the specified StateItem object in the StateBag object. |
ToString | Returns a string representing the status package object. |
The following example illustrates the concept of strings that store view state.
Let's keep a counter that can be incremented every time the page is called back by clicking a button on the page. The label control displays the value of the counter.
The tag file code looks like this:
<%@ Page Language="C#" AutoEventWireup="true" CodeBehind="Default.aspx.cs" Inherits="statedemo._Default" %><!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Transitional//EN" "http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd"><html xmlns="http://www.w3.org/1999/xhtml" > <head runat="server"> <title> Untitled Page </title> </head> <body> <form id="form1" runat="server"> <div> <h3>View State demo</h3> Page Counter: <asp:Label ID="lblCounter" runat="server" /> <asp:Button ID="btnIncrement" runat="server" Text="Add Count" onclick="btnIncrement_Click" /> </div> </form> </body></html>
The code-behind file for this instance looks like this:
public partial class _Default : System.Web.UI.Page{ public int counter { get { if (ViewState["pcounter"] != null) { return ((int)ViewState["pcounter"]); } else { return 0; } } set { ViewState["pcounter"] = value; } } protected void Page_Load(object sender, EventArgs e) { lblCounter.Text = counter.ToString(); counter++; }}
It will produce the following results:
Control states cannot be directly modified, accessed or disabled.
When a user connects to an ASP.NET website, a new session object is created. When session state is enabled, new session state is created for each new request. This session state object becomes part of the runtime environment and is available through the page.
Session state is typically used to store application data such as inventory, supplier lists, customer records, or shopping carts. It can store the user's information and their preference information, and save the user's undecided path.
Sessions are identified and tracked by a 120-bit SessionID, passed from the client to the server and returned as a cookie or modified URL. SessionID is globally unique and random.
Session state objects are created by the HttpSessionState class, which defines a collection of session state items.
The HttpSessionState class has the following properties:
property | describe |
---|---|
SessionID | Unique session identifier. |
Item(name) | The value of the session state item with the specified name, which is the default property of the HttpSessionState class. |
Count | The number of items in the session state collection. |
TimeOut | Gets and sets the amount of time, in minutes, allowed between requests before the provider stops session state. |
The HttpSessionState class has the following methods:
method | describe |
---|---|
Add(name, value) | Adds new items to the session state collection. |
Clear | Removes all items from the session state collection. |
Remove(name) | Removes the specified item from the session state collection. |
RemoveAll | Removes all keys and values from the session state collection. |
RemoveAt | Removes the item at the specified index from the session state collection. |
A session state object is a name-value pair that can store and retrieve information from a session state object. Likewise, you can use the following code:
void StoreSessionInfo(){ String fromuser = TextBox1.Text; Session["fromuser"] = fromuser;}void RetrieveSessionInfo(){ String fromuser = Session["fromuser"]; Label1.Text = fromuser;}
The above code only stores strings in the session dictionary object, however, it can store all primitive data types and arrays composed of primitive data types, DataSet, DataTable, HashTable, and image objects, as well as any user-defined objects that inherit from ISerializable objects. kind.
The following example illustrates the concept of storing session state. There are two buttons on the page: a textbox button to enter a string and a label button to display the text stored from the last session. The tag file code looks like this:
<%@ Page Language="C#" AutoEventWireup="true" CodeFile="Default.aspx.cs" Inherits="_Default" %><!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Transitional//EN" "http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd"><html xmlns="http://www.w3.org/1999/xhtml" > <head runat="server"> <title> Untitled Page </title> </head> <body> <form id="form1" runat="server"> <div> <table> <tr> <td> <asp:Label ID="lblstr" runat="server" Text="Enter a String" > </asp:Label> </td> <td> <asp:TextBox ID="txtstr" runat="server"> </asp:TextBox> </td> </tr> <tr> <td> </td> <td> </td> </tr> <tr> <td> <asp:Button ID="btnnrm" runat="server" Text="No action button" /> </td> <td> <asp:Button ID="btnstr" runat="server" OnClick="btnstr_Click" Text="Submit the String" /> </td> </tr> <tr> <td> </td> <td> </td> </tr> <tr> <td> <asp:Label ID="lblsession" runat="server" > </asp:Label> </td> <td> </td> </tr> <tr> <td> <asp:Label ID="lblshstr" runat="server"> </asp:Label> </td> <td> </td> </tr> </table> </div> </form> </body></html>
It should look like this in the design view:
The background code is as follows:
public partial class _Default : System.Web.UI.Page { String mystr; protected void Page_Load(object sender, EventArgs e) { this.lblshstr.Text = this.mystr; this.lblsession.Text = (String)this.Session["str"]; } protected void btnstr_Click(object sender, EventArgs e) { this.mystr = this.txtstr.Text; this.Session["str"] = this.txtstr.Text; this.lblshstr.Text = this.mystr; this.lblsession.Text = (String)this.Session["str"]; }}
Execute the file and watch how it runs:
An ASP.NET application is a collection of all web pages, code, and other files in a single virtual directory on a Web server. When information is stored in application state, it is available to all users.
To provide the use of application state, ASP.NET creates an application state object for each application from the HttpApplicationState class and stores the object in server memory. This object is represented by the class file global.asax.
The application state is mainly used to store counters, other statistical data and all application data such as tax rates and discount rates, and to store the user's path to the website.
The HttpApplicationState class has the following properties:
property | describe |
---|---|
Item(name) | The value of the application entry with the specified name, which is the default property of HttpApplicationState. |
Count | The number of items in the application state collection. |
The HttpApplicationState class has the following methods:
method | describe |
---|---|
Add(name, value) | Adds new items to the application state collection. |
Clear | Removes all items from the application state collection. |
Remove(name) | Removes the specified item from the application state collection. |
RemoveAll | Removes all objects in an HttpApplicationState collection. |
RemoveAt | Removes an HttpApplicationState object from the collection found by the index. |
Lock() | Lock the application state collection so that only the current user can access it. |
Unlock() | Unlock the application state collection so that all users can access it. |
Application state data is typically maintained by handlers written for events:
Application opens
Application ends
application error
Session starts
session ended
The following code snippet shows the basic syntax for storing application state information:
Void Application_Start(object sender, EventArgs e){ Application["startMessage"] = "The application has started.";}Void Application_End(object sender, EventArgs e){ Application["endtMessage"] = "The application has ended.";}