Preserving State in Web Applications
There are number of ways that you can use to preserve the State of the Web Application. Here are some of the possible ways listed.
1) Using Cookies
2) Using Session States
3) Using Application States
4) Using HttpContext collection
5) Using ViewState
These are only some ways of storing the state of the user as well as the application. In this article we will see few of them in detail.
Using Cookies to maintain the state of the application
Cookies are created on the server side but saved on the client side. In the button click event of ‘Cookies’, write this code:
HttpCookie cName = new HttpCookie("Name");
cName.Value = txtName.Text;
Response.Cookies.Add(cName);
Response.Redirect("WebForm5.aspx");
First, we create a cookie named "cName". Since one cookie instance can hold many values, we tell the compiler that this cookie will hold "Name" value. We assign to it the value of the TextBox and finally add it in the Response stream, and sent it to the other page using Response.Redirect method.
Cookies can also have expiration time which means they can expire at some specified time or you can also set the sliding time which means that will expire is that cookies is not being used.
Using Cookieless Sessions in Asp.net
For all those users who have configured not to accept cookies they can use cookie less sessions. Here is a simple syntax of using the cookieless sessions.
sessionState
mode="Off"
stateConnectionString=
"tcpip=127.0.0.1:42424"
sqlConnectionString="data source=(local);
Integrated Security=SSPI"
cookieless="true"
timeout="20"
The only downside of using the cookieless sessions is that you cannot use the absolute urls and must code each link manually.
Using Session Variables to store the state of the application
Sessions are created as soon as the first response is being sent from the client to the server, and session ends when the user closes his browser window or some abnormal operation takes place. Here is how you can use session variables for transferring values. Below you can see a Session is created for the user and "Name" is the key, also known as the Session key, which is assigned the TextBox value.
// Session Created
Session["Name"] = txtName.Text;
Response.Redirect("WebForm5.aspx");
// The code below shows how to get the session value.
// This code must be placed in other page.
if(Session["Name"] != null)
Label3.Text = Session["Name"].ToString();
We can also store collections in the Session variables. These collections can be ArrayList or HashTables. Later you can use the casting to retrieve those collections.
Configuring Session State
You can configure the session state in your web.config file. This means that the settings that you will do in the web.config file will be affected to the whole application. Let’s see how we can do this:
Configuring In-Process Mode
In-process is the default session state mode. To use in-process mode, set the mode attribute of the
The following shows a sample configuration setting for in-process mode.
timeout="20"/>
(msdn)
Configuring State Server Mode
To use State Server, you must first make sure ASP.NET state service is running on the remote server used for the session store. This service is installed with ASP.NET and Visual Studio .NET at the following location:
systemroot\Microsoft.NET\Framework\versionNumber\aspnet_state.exe
Next, set the mode attribute of the
The following shows a sample configuration setting for State Server mode.
cookieless="false"
timeout="20"/>
(msdn)
Configuring SQL Server Mode
To use SQL Server, first run either InstallSqlState.sql or InstallPersistSqlState.sql on the computer with SQL Server that will store the session state. Both scripts create a database called ASPState that includes several stored procedures. The difference between the scripts is where the ASPStateTempApplications and ASPStateTempSessions tables are placed. The InstallSqlState.sql script adds these tables to the TempDB database, which loses session data if the computer is restarted. The InstallPersistSqlState.sql script, on the other hand, adds these tables to the ASPState database, which allows session data to be retained when the computer is restarted.
Both of these script files are installed by default at the following location:
systemroot\Microsoft.NET\Framework\versionNumber
Next, set the mode attribute of the
The following shows a sample configuration setting for SQL Server mode.
cookieless="false"
timeout="20"/>
In SQL Server mode, session state can also be configured to work in a failover cluster. A failover cluster is two or more identical, redundant Web servers that store their session data on a separate computer in a SQL Server database. If a Web server fails, another server in the cluster can take over and serve requests without session data loss. To configure a failover cluster, set the
(msdn)
Using HttpContext to store the values
You can also use HttpContext to retrieve values from pages. The values are retrieved using properties or methods. It’s a good idea to use properties since they are easier to code and modify. In your first page, make a property that returns the value of the TextBox.
public string GetName
{
get { return txtName.Text; }
}
We will use Server.Transfer to send the control to a new page. Note that Server.Transfer only transfers the control to the new page and does not redirect the browser to it, which means you will see the address of the old page in your URL. Simply add the following line of code in ‘Server.Transfer’ button click event:
Server.Transfer("WebForm5.aspx");
Now, let’s go to the page where the values are being transferred, which in this case is "webForm5.aspx".
// You can declare this Globally or in any event you like
WebForm4 w;
// Gets the Page.Context which is Associated with this page
w = (WebForm4)Context.Handler;
// Assign the Label control with the property "GetName" which returns string
Label3.Text = w.GetName;
Using Application State to store the application level values
Sometimes, we need to access a value from anywhere in our page. For that, you can use Application variables. Here is a small code that shows how to do that. Once you created and assigned the Application variable, you can retrieve its value anywhere in your application.
// This sets the value of the Application Variable
Application["Name"] = txtName.Text;
Response.Redirect("WebForm5.aspx");
// This is how we retrieve the value of the Application Variable
if( Application["Name"] != null )
Label3.Text = Application["Name"].ToString();
Page Level State to Store the Session
This is one of the coolest feature of the Asp.net. Its called ViewState object. ViewState can store an object type which means it can store any type of class variables since they all are derived from the object class. ViewState can only be used if the page is posting back to itself. Here is a simple example of putting values on the view state:
ViewState["MyViewState"] = myVariable;