You are on page 1of 74

Application State in ASP.

Net
We all know that the web uses the HTTP protocol and that the HTTP protocol is a
stateless protocol, in other words when a client sends a request to the server, an
instance of the page is created and the page is converted to HTML format and then the
server returns the response and then the instance of the page and the value of the
control is destroyed. So if we have a requirement to store the value of controls then a
State Management technique is used.

Application State Life Cycle

Step 1 : When the Browser sends a request to the web server and the server receives
the the request it first checks the extension to determine whether or not it is ISAPI
because this request can only be handled by the ISAPI extension; if the extension is
different then the request is handled by the server itself.

Step 2 : After receiving the request the Application Manager creates an application
domain. In the application domain an instance of the class HostingEnvironment is
created that provides access to information about all application resources.
Step 3 : After creating the application domain, ASP.NET initializes the basic objects as
HTTPContext, HTTPRequest and HTTPResponse. HTTPContext holds objects to the
specific application request as HTTPRequest and HTTPResponse.HTTPRequest
contains all the information regarding the current request like cookies, browser
information and so on and the HTTPResponse contains the response that is sent to the
client.

Step 4 : Here all the basic objects are being initialized and the application is being
started with the creation of the HTTPApplication class.

Step 5 : Then events are executed by the HTTPApplication class for any specific
requirement. Here is a list of events:
Global.asax file: the Global.asax file is used for handling application events or methods.
It always exists in the root level. Events are one of the following of the 2 types in the
Global application:

1. Events that will be raised on a certain condition.

2. Events that will be raised on every request.

The application will be started only once; if 10 users send a request then 10 user
sessions are created. The events of the Global.asax file are:

1. Application_Start() : This method is invoked initially when first application


domain is created.

2. Session_Start() : This method is called every time a session is start.

3. Application_BeginRequest() : After an application has started the first method


Application_BeginRequest() is executed for every user.

4. Application_AuthenticateRequest() : It checks to determine whether or not the


user is valid.

5. Application_Error() : Whenever an unhandled exception occurs then this event


will be called.
6. Session_End() : When a user session is ended and all the data related to a
specific user is cleared then the Session_End() event is called.

7. Application_End() : This method is called before the application ends. This can
take place if IIS is restarted or the application domain is changing.

8. Application_Disposed() : This event is called after the application will be shut


down and the .NET GC is about to reclaim the memory it occupies. Although this
is very late to perform any clean-up but we can use it for safety purposes.

ASP.NET Application State real-life example

Now I am explaining the real-life example. If you want to see the number of users online
then we need to use Application State.

Step 1 : Open Visual Studio 2010.

Step 2 : Then click on "New Project" > "Web" > "ASP.NET Empty Web Application" .

Step 3 : Now click on Solution Explorer.


Step 4 : Now right-click on "Add" > "New Item" > "Web Form" and add the name of the
web form.

Step 5 : Now add the Global.asax file. Again go to Solution Explorer and "Add" > "New
Item" > "Global Application Class".
Step 6 : Now to configure the session we need to use the web.config file as in the
following:

1. <sessionState mode="InProc" timeout="20" cookieless="true"></sessionState>

Step 7 : Now to count the number of users online we need to use the global.asax file as
in the following:

1. protected void Application_Start(object sender, EventArgs e)

2. {

3. //this event is execute only once when application start and it stores the server memory u
ntil the worker process is restart

4. Application["user"] = 0;

5. }

6. protected void Session_Start(object sender, EventArgs e)

7. {

8. //when session in start application variable is increased by 1

9. Application.Lock();

10. Application["user"] = (int) Application["user"]+1;

11. Application.UnLock();
12. }

13. protected void Session_End(object sender, EventArgs e)

14. {

15. //when session in end application variable is decrease by 1

16. Application.Lock();

17. Application["user"] = (int)Application["user"] - 1;

18. Application.UnLock();

19. }

Step 8 : Now to show the online users we need to use a web form as in the following:

1. protected void Page_Load(object sender, EventArgs e)

2. {

3. Response.Write("The num of users online=" + Application["user"].ToString());

4. }

Output

When the same request is sent to the server with a different browser then the number of
online clients is also not increased because the browser binds with the session id so
both of the tabs have the same session id so the server knows that the request comes
from the same user. If we change the session id from the URL and again refresh then
the number of online clients is increased by one because the server thinks that the
request comes from a different browser.

Important points of Application State variables

1. Application State variables are available across all pages and all sessions.
Application State variables are like multi-user Global data.

2. Application variables are stored on a web server.


3. Application State variables are cleared, only when the process hosting the
application is restarted, that is when the application is ended.

4. Application State variables do not support web farms and web gardens:
Application State variables are not supported be web farms.

A client sends a request and the request goes to the load balancer and the load
balancer sends a request to web server1 and the Application State variables are
stored in a web server1. If the subsequent request is sent by the client again and
the load balancer sends a request to web server2 and the Application State
variables are not stored in web server2 then something. Web servers do not
share application state variables.

5. Application State variables have a concurrency problem so we need to


synchronize the method by using the lock and unlock methods. So multiple
thread problems are resolved since only one thread can do the work.

6. An application variable is used only when the variable needs to have global
access and when you need them for the entire time, during the lifetime of an
application.
How to create Application state?

It's very easy to create application state in the ASP.NET application. I


am going to take you to write simple application state program now.

Example 1: In the Global.asax page


void Application_Start(object sender, EventArgs e)
{
// Code that runs on application startup
Application["LoginID"] = "annathurai";
Application["DomainName"] = "www.annathurai.com";
}

Example 2: Inside the .aspx page


protected void Page_Load(object sender, EventArgs e)
{

// Code that runs on page load

Application["LoginID"] = "annathurai";
Application["DomainName"] = "www.annathurai.com";
}

How to retrieve application state?

It's very easy to retrieve application state in the ASP.NET application. I


am going to take you to write simple application state program now.
string loginID=string.Empty;
loginID = Application["LoginID"].ToString();

string loginID = string.Empty;


loginID = Application.GetKey(0);

We can retrieve all application variable on the currently running application's keys by
using HttpApplicationState class.

HttpApplicationState appState = null;


appState = Application.Contents;

String[] StateVars = new String[appState.Count];


StateVars = appState.AllKeys;

How to remove application variable?


We have three methods to remove application variable from the ASP.NET application.

Application.Remove("LoginID");
Application.RemoveAt(0);
Application.RemoveAll();
How to implement Synchronization in application state?
We can avoid deadlock occurrence while we updating application variable
by multiple users with help of Lock() and UnLock().

Application.Lock();
Application["LoginID"] = "annathurai";
Application["Domain"] = "www.annathurai.com";
Application.UnLock();
Advantages of application state:

Application object memory relased when we removed.


Multi user can able to access application variable.
To avoid deadlock or conflict we should use Lock and Unlock when we use
write or update in the application object.
Other application can't access this application values.

Disadvantages of application state:

Application variable will exists until exit our application.


If we do not have Lock() and Unlock, deadlock will occur.
Its gloable variable so anyone can access within this application.

Using Application State to Check User Visits on


a Website

Step 1

Open your Visual Studio 2010 and create an Empty Website, provide a suitable name
(Applicationstate_demo).

Step 2

In Solution Explorer you get your empty website, then add a Web Form and Global.asax
file. By going as in the following.

For Web Form

applicationstate_demo (your empty website) then right-click then select Add New Item ->
Web Form. Name it applicationstate.aspx.

For Global.asax
applicationstate_demo (your empty website) then right-click then select Add New Item ->
Global Application Class.

Figure 1: Global Class

Global.asax Code

1. <%@ Application Language="C#" %>

2. <script runat="server">

3. void Application_Start(object sender, EventArgs e)

4. {

5. // Code that runs on application startup

6. Application["VisitorCount"] = 0;

7. }

8. void Application_End(object sender, EventArgs e)

9. {

10. // Code that runs on application shutdown

11. }

12. void Application_Error(object sender, EventArgs e)

13. {

14. // Code that runs when an unhandled error occurs

15. }

16. void Session_Start(object sender, EventArgs e)

17. {

18. // Code that runs when a new session is started


19. Application["VisitorCount"] = (int)Application["VisitorCount"] + 1;

20. }

21. void Session_End(object sender, EventArgs e)

22. {

23. // Code that runs when a session ends.

24. // Note: The Session_End event is raised only when the sessionstate mode

25. // is set to InProc in the Web.config file. If session mode is set to StateServer

26. // or SQLServer, the event is not raised.

27. }

28. </script>

As the application starts we have visitor count = 0. As we proceed we increment the


visitor count to +1.

Figure 2: Code

As the session starts we set the visitor count to +1 in the event of the session start.

Figure 3: Session Start

This is my welcome page. You can make your own or you can just make it blank and
print the label for the total of visits.

1. <%@ Page Language="C#" AutoEventWireup="true" CodeFile="Default.aspx.cs" Inherits=


"_Default" %>

2. <!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Transitional//EN" "http://www.w3.org/TR/


xhtml1/DTD/xhtml1-transitional.dtd">
3. <html

4. xmlns="http://www.w3.org/1999/xhtml">

5. <head runat="server">

6. <title></title>

7. <style type="text/css">

8. .style1

9. {

10. text-align: center;

11. }

12. .style2

13. {

14. font-size: xx-large;

15. }

16. </style>

17. </head>

18. <body bgcolor="#ffffcc">

19. <form id="form1" runat="server">

20. <div class="style1">

21. <strong>

22. <span class="style2">Welcome to Active DotNet

23. <br />

24. <br />

25. </span>

26. </strong>

27. <br />

28. <br />

29. <br />

30. <br />


31. <asp:Image ID="Image1" runat="server" Height="350px" ImageUrl="~/1.jpg" /
>

32. <br />

33. <br />

34. </div>

35. <p>

36. <asp:Label ID="Label2" runat="server"

37. style="text-align: center; font-weight: 700; font-size: large"></asp:Label>

38. </p>

39. </form>

40. </body>

41. </html>

Figure 4: Output 1

Here in the label we will print the total visiting. Look the following image.
Figure 5: Output 2

Figure 6: Output 3

Cookies in ASP.NET
I will explain you with the help of a program how to store cookies and how to retrieve the
cookies.

Code for Default.aspx design page

<%@ Page Language="C#" AutoEventWireup="true" CodeFil


e="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>
<asp:Button ID="Button1" runat="server" Text="Store
Cookies" OnClick="Button1_Click" />
</div>
</form>
</body>
</html>

Code for Default.aspx.cs page

using System;
using System.Configuration;
using System.Data;
using System.Linq;
using System.Web;
using System.Web.Security;
using System.Web.UI;
using System.Web.UI.HtmlControls;
using System.Web.UI.WebControls;
using System.Web.UI.WebControls.WebParts;
using System.Xml.Linq;

public partial class _Default : System.Web.UI.Page


{
protected void Page_Load(object sender, EventArgs e)
{

HttpCookie myCookie;

protected void Button1_Click(object sender, EventArgs e)


{
myCookie = new HttpCookie("test");
myCookie.Values["name"] = "Puran Singh Mehra";
myCookie.Values["age"] = "30+";
myCookie.Values["Profession"] = "Software";
myCookie.Values["Address"] = "India";

myCookie.Expires = DateTime.Now.AddHours(1);
Response.Cookies.Add(myCookie);
Response.Redirect("Default2.aspx");
}
}

Output 1:
Code for Default2.aspx design page

<%@ Page Language="C#" AutoEventWireup="true" CodeFil


e="Default2.aspx.cs"Inherits="Default2" %>
<!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>
<asp:Button ID="Button1" runat="server" OnClick="Button1_Click" Style="top: 23
1px;
left: 476px; position: absolute; height: 26px; width: 116px" Text="Show
Cookie" />
</div>
</form>
</body>
</html>
Code for Default2.aspx.cs design page

using System;
using System.Collections;
using System.Configuration;
using System.Data;
using System.Linq;
using System.Web;
using System.Web.Security;
using System.Web.UI;
using System.Web.UI.HtmlControls;
using System.Web.UI.WebControls;
using System.Web.UI.WebControls.WebParts;
using System.Xml.Linq;

public partial class Default2 : System.Web.UI.Page


{
protected void Page_Load(object sender, EventArgs e)
{
foreach (string str in Request.Headers)
{
Response.Write(str + "=" + Request.Headers[str] + "<br>");
}

Response.Write("________________________________________________" + "<br>"
);
}

protected void Button1_Click(object sender, EventArgs e)


{
foreach (string str in Request.Cookies["test"].Values)
{
Response.Write(str + "=" + Request.Cookies["test"].Values[str] + "<br>");
}
}
}

Output 2:

Output 3:
Cookies Merits

Data is stored on client side, so it is faster. Cookies are best used to store small amounts of
data, for example it can store User ID and Password. This UserID and Password can then
be used to identify the user and read user information from a database or other data store. It
is recommended to encrypt a password before it is stored in a cookie as cookies are not
secured.

Cookies Demerits

Security problem as they are stored on client.


Client can delete cookie any time.
Browsers also impose limitations on how many cookies your site can store on the user's
computer.
Cookie can only store 4kb of data.
Data is not authenticated i.e. client can delete the cookie.

Cookies in ASP.NET

Type of Cookies?
1. Persist Cookie - A cookie has not have expired time Which is called as Persist
Cookie

2. Non-Persist Cookie - A cookie has expired time Which is called as Non-Persist


Cookie

How to create a cookie?

Its really easy to create a cookie in the Asp.Net with help of Response object or
HttpCookie

Example 1:

HttpCookie userInfo = new HttpCookie("userInfo");


userInfo["UserName"] = "Annathurai";
userInfo["UserColor"] = "Black";
userInfo.Expires.Add(new TimeSpan(0, 1, 0));
Response.Cookies.Add(userInfo);

Example 2:

Response.Cookies["userName"].Value = "Annathurai";
Response.Cookies["userColor"].Value = "Black";

How to retrieve from cookie?

Its easy way to retrieve cookie value form cookes by help of Request object.

Example 1:

string User_Name = string.Empty;


string User_Color = string.Empty;
User_Name = Request.Cookies["userName"].Value;
User_Color = Request.Cookies["userColor"].Value;

Example 2:

string User_name = string.Empty;


string User_color = string.Empty;
HttpCookie reqCookies = Request.Cookies["userInfo"];
if (reqCookies != null)
{
User_name = reqCookies["UserName"].ToString();
User_color = reqCookies["UserColor"].ToString();
}

When we make request from client to web server , the web server process the request
and give the lot of information with big pockets which will have Header information,
Metadata, cookies etc., Then repose object can do all the things with browser.

Cookie's common property:

1. Domain => Which is used to associate cookies to domain.

2. Secure => We can enable secure cookie to set true(HTTPs).

3. Value => We can manipulate individual cookie.

4. Values => We can manipulate cookies with key/value pair.

5. Expires => Which is used to set expire date for the cookies.

Advantages of Cookie:

1. Its clear text so user can able to read it.

2. We can store user preference information on the client machine.

3. Its easy way to maintain.

4. Fast accessing.

Disadvantages of Cookie

1. If user clear cookie information we can't get it back.

2. No security.

3. Each request will have cookie information with page.

How to clear the cookie information?

1. we can clear cookie information from client machine on cookie folder

2. To set expires to cookie object


userInfo.Expires = DateTime.Now.AddHours(1);
It will clear the cookie with one hour duration.
How to Create Session Variable without
Cookies?

In this example you use the textbox value in other page without cookie in javascript.

Step:1 Your first page name Default page like this

<%@ Page Language="C#" AutoEventWireup="true" CodeFil


e="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>
<script type="text/javascript" src="JavaScript/sessvars.js"></script>
<script type="text/javascript">
function PreSaveAction()
{
//alert(document.getElementById("txtname").value);
sessvars.username = document.getElementById("txtname").value;
return true;
}

</script>

</head>
<body>
<form id="form1" runat="server">
<div>
<table>
<tr>
<td>
Enter Your
Name:<asp:TextBox ID="txtname" runat="server"></asp:TextBox>
</td>
</tr>
<tr>
<td>
<input id="btnsave" type="submit" value="Save Your
Name" runat="server"onclick="PreSaveAction()" onserverclick="btnsave_ServerClick"/>

</td>
</tr>
</table>
</div>
</form>
</body>
</html>

Step 2: .cs file like this

using System;
using System.Data;
using System.Configuration;
using System.Web;
using System.Web.Security;
using System.Web.UI;
using System.Web.UI.WebControls;
using System.Web.UI.WebControls.WebParts;
using System.Web.UI.HtmlControls;

public partial class _Default : System.Web.UI.Page


{
protected void Page_Load(object sender, EventArgs e)
{

}
protected void btnsave_ServerClick(object sender, EventArgs e)
{
Response.Redirect("~/Default2.aspx");
}
}

Step: 3 Your Second page where the you can reuse your textbox value

<%@ Page Language="C#" AutoEventWireup="true" CodeFil


e="Default2.aspx.cs"Inherits="Default2" %>

<!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>
<script type="text/javascript" src="JavaScript/sessvars.js"></script>
<script type="text/javascript">
function GetUserName()
{
var newusername = sessvars.username;
document.getElementById("lblusername").innerHTML = newusername;
if(sessvars.username!=undefined)
{
sessvars.$.clearMem();
}
}
</script>
</head>
<body>
<form id="form1" runat="server">
<div>
<asp:Label ID="lblusername" runat="server" Text=""></asp:Label>
<input id="btnsave" type="button" value="Displayuser" onclick="GetUserName()"
/>
</div>
</form>
</body>
</html>

using System;
using System.Data;
using System.Configuration;
using System.Collections;
using System.Web;
using System.Web.Security;
using System.Web.UI;
using System.Web.UI.WebControls;
using System.Web.UI.WebControls.WebParts;
using System.Web.UI.HtmlControls;

public partial class Default2 : System.Web.UI.Page


{
protected void Page_Load(object sender, EventArgs e)
{
}
}

Creating a cookie :

On PageOne.aspx we have placed a TextBox and a button and on the click of the
button, we are going to store the value in the textbox in a cookie.

protected void btnStoreCookie_Click(object sender, EventArgs e)


{
Response.Cookies["Username"].Value = txtUsername.Text;
Response.Cookies["Username"].Expires = DateTime.Now.AddMinutes(5);
}
The RESPONSE object has the Cookies collecton in which we can store the
values, the above given code creates a cookie "username" and stores the text
box value in it.
The expiration time is set to 5 minutes. After 5 minutes, the cookie gets
automatically deleted from the user's disk.

Retrieve a cookie value :

Now we will read a cookie value on PageTwo.aspx page. For every request, the
cookie is sent to the server from the client in a page request. So we can read the
cookie value using a RESPONSE object.

protected void Page_Load(object sender, EventArgs e)


{
if (Request.Cookies["Username"] != null)
{
Response.Write("The currently logged in user is : " +
Request.Cookies["Username"].Value);
}
else
{
Response.Write("No cookie found");
}
}

Now we test if we have created a cookie successfully on not!

Run the project to browse the PageOne.aspx page. Enter some value in the text
box and click the store cookie button.

Now close the browser. Run the project with PageTwo.aspx as a start page or
naviagate to PageTwo.aspx in the browser.

You will see the value that you stored into the cookie is shown.

Now, browse the PageTwo.aspx page after 5 minutes and you will see that the
cookie has been deleted. A cookie can be deleted explicitly. This can be done by
setting the expires property to a negative value
protected void btnDeleteCookie_Click(object sender, EventArgs e)
{
HttpCookie deleteCookie = new HttpCookie("Username");
Response.Cookies.Add(deleteCookie);
deleteCookie.Expires = DateTime.Now.AddDays(-1);
}

Cookies are recommended only when the server needs to store a very small
piece of information on the client side.

This information should never be critical/personal/or some information that


should not be disclosed to intruders.

Also, the server code cannot always rely on the cookie information as the
cookies can also be deleted by the client.

Number of cookies that can be stored depends upon the browser. Also, the size
of cookies in a browser are generally limited to 4kb.

Introduction to Cookies in ASP.Net

Basically Cookies are one of the following 2 types:

1. Persistent Cookies: Persistent Cookies are Permanent Cookies stored as a text


file in the hard disk of the computer.

2. Non-Persistent Cookies: Non-Persistent cookies are temporary. They are also


called in-memory cookies and session-based cookies. These cookies are active
as long as the browser remains active, in other words if the browser is closed
then the cookies automatically expire.

Now I am showing a practical difference between Persistent and Non-Persistent Cookies


with an example.
Step 1: Open Visual Studio 2010.
Step 2: Now go to "New Project" > "Web" > "ASP.NET Empty Web Application".

Step 3: Now click on the Solution Explorer.

Step 4: Now right-click on "Add" > "New Item" > "Web Form" and add the name of the
Web Form.
Step 5: After adding the Web Form you will write the following code:

1. <%@ Page Language="C#" AutoEventWireup="true" CodeBehind="Default.aspx.cs" Inheri


ts="Cookies._Default" %>

2.

3. <!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Transitional//EN" "http://www.w3.org/TR/


xhtml1/DTD/xhtml1-transitional.dtd">

4. <html xmlns="http://www.w3.org/1999/xhtml">

5. <head id="Head1" runat="server">

6. <title></title>

7. <style type="text/css">

8. .style1

9. {

10. width: 100%;

11. }

12. .style2

13. {
14. width: 179px;

15. }

16. </style>

17. </head>

18. <body>

19. <form id="form1" runat="server">

20. <div>

21. <table class="style1">

22. <tr>

23. <td class="style2">

24. Welcome To default Page

25. </td>

26. <td>

27.

28. </td>

29. </tr>

30. <tr>

31. <td class="style2">

32. User Name

33. </td>

34. <td>

35. <asp:TextBox ID="tbUserName" runat="server"></asp:TextBox>

36. </td>

37. </tr>

38. <tr>

39. <td class="style2">

40. Password

41. </td>

42. <td>
43. <asp:TextBox ID="tbPwd" runat="server"></asp:TextBox>

44. </td>

45. </tr>

46. <tr>

47. <td class="style2">

48. <asp:Button ID="Button1" runat="server" OnClick="Button1_Click" Text="Sub


mit" />

49. </td>

50. <td>

51.

52. </td>

53. </tr>

54. </table>

55. </div>

56. </form>

57. </body>

58. </html>

Code: This code also shows how to write the cookies.

1. protected void Button1_Click(object sender, EventArgs e)

2. {

3.
//create a cookie by using HttpCookie class and add the name of the cookie that is Democo
okie

4. HttpCookie cookie = new HttpCookie("Democookie");

5. //assign the textBoxes Value on introduction-of-cookies

6. cookie["UserName"] = tbUserName.Text;

7. cookie["Pwd"] = tbPwd.Text;

8. //Write the Cookies on the client machine

9. Response.Cookies.Add(cookie);

10. //Redirect the page to other page


11. Response.Redirect("WebForm2.aspx");

12. }

Step 6: Now the WebForm2.aspx Web Form is also added and after the following Code
is:

1. <%@ Page Language="C#" AutoEventWireup="true" CodeBehind="WebForm2.aspx.cs" In


herits="Cookies.WebForm2" %>

2.

3. <!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Transitional//EN" "http://www.w3.org/TR/


xhtml1/DTD/xhtml1-transitional.dtd">

4. <html xmlns="http://www.w3.org/1999/xhtml">

5. <head id="Head1" runat="server">

6. <title></title>

7. <style type="text/css">

8. .style1

9. {

10. width: 345px;

11. }

12. .style2

13. {

14. width: 204px;

15. }<a href="WebForm2.aspx">WebForm2.aspx</a>

16. </style>

17. </head>

18. <body>

19. <form id="form1" runat="server">

20. <div>

21. <table class="style1">

22. <tr>

23. <td class="style2">


24. Welcome to WebForm2

25. </td>

26. <td>

27.

28. </td>

29. </tr>

30. <tr>

31. <td class="style2">

32. User Name

33. </td>

34. <td>

35. <asp:Label ID="lblUname" runat="server"></asp:Label>

36. </td>

37. </tr>

38. <tr>

39. <td class="style2">

40. Password

41. </td>

42. <td>

43. <asp:Label ID="LblPwd" runat="server"></asp:Label>

44. </td>

45. </tr>

46. <tr>

47. <td class="style2">

48.

49. </td>

50. <td>

51.

52. </td>
53. </tr>

54. </table>

55. </div>

56. </form>

57. </body>

58. </html>

Code: This code will show how to read cookies:

1. protected void Page_Load(object sender, EventArgs e)

2. {

3. //Retrive the Demointroduction-of-cookies on the client's pc

4. HttpCookie cookie = Request.Cookies["Democookie"];

5. if (cookie != null)

6. {

7. //assign the introduction-of-cookies value on the labelk

8. lblUname.Text = cookie["UserName"];

9. LblPwd.Text = cookie["Pwd"];

10. }

11. }

Output

From this output are the following 3 important points:


1. If the same URL is open in a new tab in the same browser then it also provides
the same output.

2. Now when I close the browser and again open the browser and open the same
URL then I also don't get the same output, in other words the cookies expire that
are the Non-Persistent Cookies.

3. For Persistent Cookies we need to add the Expiration time of the cookies, in
other words the browser manages the time of the cookies and if we close the
browser then we also get the same output and the cookie will not expire; they are
Persistent Cookies.

1. protected void Button1_Click(object sender, EventArgs e)

2. {

3.
//create a cookie by using HttpCookie class and add the name of the cookie that is Democo
okie

4. HttpCookie cookie = new HttpCookie("Democookie");

5. //assign the textBoxes Value on introduction-of-cookies

6. cookie["UserName"] = tbUserName.Text;

7. cookie["Pwd"] = tbPwd.Text;

8. //Write the Cookies on the client machine

9. Response.Cookies.Add(cookie);

10. //add the Expiration Time That is 20 days

11. cookie.Expires = DateTime.Now.AddDays(20);

12. //Redirect the page to other page

13. Response.Redirect("WebForm2.aspx");

14. }

Deleting The Cookies: Cookies cannot be removed directly because it is on the user's
computer. So we can delete cookies using:

Response.Cookies["Democookie"].Expires = DateTime.Now.AddDays(-1);

Multivalued Cookies: A single Cookie can store multiple values and those values are
like a subkey for a key.
Now I am showing how to write a Multivalued Cookie.

Step 5: The remaining steps are the same and add the code in the code behind in the
Default.aspx.

1. protected void Button1_Click(object sender, EventArgs e)

2. {

3. //Write Cookie

4. HttpCookie cookie = new HttpCookie("Democookie");

5. Response.Cookies["userinfo"]["UserName"] = tbUserName.Text;

6. Response.Cookies["userinfo"]["Pwd"] = tbPwd.Text;

7. Response.Cookies.Add(cookie);

8. cookie.Expires = DateTime.Now.AddDays(30);

9. Response.Redirect("WebForm2.aspx");

10. }

Step 6: Now add the code in the Code Behind in WebFrorm2.aspx.

1. protected void Page_Load(object sender, EventArgs e)

2. {

3. //Read the Cookie

4. HttpCookie cookie = Request.Cookies["Democookie"];

5. if (cookie != null)

6. {

7. lblUname.Text=Request.Cookies["userinfo"]["UserName"];

8. LblPwd.Text=Request.Cookies["userinfo"]["Pwd"];

9. }

10. }

Reasons to use Multivalued Cookies:

1. It is convenient to keep a related subkey that hs same Expiration Time is in a


single cookie.
2. According to cookie limitations, the size of a cookie file is the limit.

Controlling Cookies Scope: For a specific site all the cookies are stored in a client's
machine. If the client requests a page of the site then the cookies are sent to the server
and it means that every page of the site gets all the introduction-of-cookies. To resolve
these problems, we can set the scope of the introduction-of-cookies in 2 ways:

1. Limit the scope of the cookie on the server: To limit the Cookies Store on the
server set the property as in the following:

cookie.Path = "/Indexpage";

The path can either be a physical path under the Site Root or a Virtual Path. By
using this Path Property we can set the path that all the cookies are available in
in the index page.

For example if your site is called www.xyz.com then the Cookies are created and
will be available to the page with the path https://www.xyz.com/Application1/ and
the cookies will not be available to the page in other applications, such as
https://www.xyz.com/Application2/.

2. By using a domain: By default cookies are stored in the domain. By using the
Domain Property we can set the specific subdomain and all the cookies are
available on that page only.

Response.Cookies["Democookie"].Domain = "xyz.com";

List of properties containing the HttpCookies Class:

1. Domain: Using these properties we can set the domain of the cookie.

2. Expires: This property sets the Expiration time of the cookies.

3. HasKeys: If the cookies have a subkey then it returns True.

4. Name: Contains the name of the Key.

5. Path: Contains the Virtual Path to be submitted with the Cookies.

6. Secured:If the cookies are to be passed in a secure connection then it only


returns True.

7. Value: Contains the value of the cookies.


Limitation of the Cookies

1. The size of cookies is limited to 4096 bytes.

2. A total of 20 cookies can be used in a single website.

The following describes how to check whether or not the browser accepts cookies.

To check the Browser Capabilitis a property of the HttpRequest class is


Request.Browser.Cookies. If it returns true then the browser supports cookies.

1. //if the request Goes To server

2. if (!IsPostBack)

3. {

4. // These Property Shows the capability of the Browser.If it returns true then Browser Supp
ort Otherwise It goes to else condition

5. if (Request.Browser.Cookies)

6. {

7. //First time the QueryString Value will be null

8. if (Request.QueryString["cookie"] == null)

9. {

10. //write the Cookies

11. HttpCookie cookie = new HttpCookie("TestOfCookie", "1");

12. //add the introduction-of-cookies

13. Response.Cookies.Add(cookie);

14. //redirect the same page

15. Response.Redirect("Default.aspx?cookie=1");

16. }

17. else

18. {

19. //On the Second Time QueryString Value is not Null

20. //read the introduction-of-cookies

21. HttpCookie cookie = Request.Cookies["TestOfCookie"];


22. //check that whether the Cookies are enable or disable on client's machine

23. if (cookie == null)

24. {

25. Response.Write("Your Browser Has Disabled The Cookie");

26. }

27. }

28. }

29. else

30. {

31. Response.Write("Your Browser Doesn't Support Cookie");

32. }

33. }

Disadvantage of the Cookies

1. Cookies are stored in the user's computer so the user can change the cookies
before the browser is sent to the server.

2. The sensitive data storage in a cookie are not in the hands of the user. It means
that the user's Personal Information Store in a cookie, like user name, password,
credit card number or someone who might somehow steal the cookies.
Security of the Cookies: Cookies are sent between the browser and the server as
plain text and the for security we can set the Property Secure but the cookies are
transmitted only if the connection uses Secure Sockets Layer (SSL). When the
cookies are transferred they are SSL encrypted so that no one can read the
Information of the cookie.

Cookies In ASP.NET

A cookie is a small text based program which stores the information on client machine.
This information can be accessed later on when a user visits the same website and
same browser. This information is stored on the clients browser for a temporary
period. Cookies should not be used for storing confidential information like passwords.

There are 2 types of cookies:


1. Session Cookie/Browser cookie:

By default the cookie values are stored only in the browser once the browser is
closed the cookie values are lost. These cookies are stored only for temporary
period and are called session cookies.

2. Persistent Cookies:

Persistent cookies are the cookies where the cookie values are stored on the
local disk for a specific period

There are 2 methods for interacting with the cookies:

1. Response & request cookies

2. Http cookies

Response object cookies are used to send the cookie information from server to client
browser. Request object cookies are used to read the cookie information from client to
server.

Http Cookie

It provides an object oriented approach for working with the cookies. It consists of a
class called HttpCookie through which cookies are handled.

Example
Cookies.aspx.cs

1. using System;

2. using System.Collections.Generic;

3. using System.Linq;

4. using System.Web;

5. using System.Web.UI;

6. using System.Web.UI.WebControls;

7.

8. namespace WebApp7am

9. {

10. public partial class cookies : System.Web.UI.Page

11. {

12. protected void Page_Load(object sender, EventArgs e)

13. {

14. if (IsPostBack == false)

15. {

16. HttpCookie cookie;

17. cookie = Request.Cookies["usercookie"];


18. if (cookie != null)

19. {

20. TextBox1.Text = cookie.Value;

21. }

22. }

23.

24. }

25.

26. protected void btnSignIn_Click(object sender, EventArgs e)

27. {

28. if(CheckBox1.Checked==true)

29. {

30. HttpCookie cookie = new HttpCookie("usercookie");

31. cookie.Value = TextBox1.Text;

32. cookie.Expires = DateTime.Now.AddDays(2);

33. Response.Cookies.Add(cookie);

34. }

35. Response.Redirect("default.aspx");

36. }

37. }

38. }

Note:

btnSignIn_click:

When a user clicks on the signin button a postback occurs and the click event checks
the status of the checkbox. If the checkbox is checked then a cookie is created with the
value entered in the textbox and an expiry is assigned for a period of 2 days. If the
checkbox is unchecked then no cookie is created.

Page_load:
Whenever the page is executed this event will get fired and it checks the status of the
postback. If ispostback is false ie.the user has executed the page for the first time and
the program will check the cookie in the client machine and if it exists reads the cookie
into the textbox. This will not executed when the user clicks on the button (when the
postback occurs).

View cookies in Google chrome

1. Go to Settings:

2. Scroll to the Privacy section, then click Content Settings.


3. Click on All cookies and site data.
4. Here you canview/remove cookie or remove all cookies. Click on the labels to
see details.

What is View State and How it Works in ASP.Net

State Management Techniques

They are classified into the following 2 categories:

Now I am explaining what View State is.

View State

View State is the method to preserve the Value of the Page and Controls between round
trips. It is a Page-Level State Management technique. 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.

Now I am showing you an examle of what the problem is when we don't use view state.

Step 1: Open Visual Studio 2010.

Step 2: Then click on "New Project" > "Web" >"ASP.NET Empty Web Application".

Step 3: Now click on Solution Explorer.


Step 4: Now right-click on the "ADD" > "New Item" > "Web Form" and add the name of
the Web Form just like I did in WebForm6.aspx.
Step 5: After adding the WebForm6.aspx you will see the following code:

<%@ page language="C#" autoeventwireup="true" codebehin


d="WebForm6.aspx.cs"inherits="view_state.WebForm6" %>

<!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></title>
</head>
<body>
<form id="form1" runat="server">
<div>
User Name:-<asp:textbox id="TextBox1" runat="server"></asp:textbox>
<br />
Password&nbsp; :-<asp:textbox id="TextBox2" runat="server"></asp:textbox>
<br />
<asp:button id="Button1" runat="server" onclick="Button1_Click" text="Submit" /
>
<asp:button id="Button3" runat="server" onclick="Button3_Click" text="Restore" /
>
</div>
</form>
</body>
</html>

Code: Now write the code as in the following:

//Declaration of a and b
public string a, b;
protected void Button1_Click(object sender, EventArgs e)
{
//TextBox1 and TextBox2 Value is Assigning on the variable a and b
a = TextBox1.Text;
b = TextBox2.Text;
//after clicking on Button TextBox value Will be Cleared
TextBox1.Text = TextBox2.Text = string.Empty;
}

protected void Button3_Click(object sender, EventArgs e)


{
//value of variable a and b is assingning on TextBox1 and Textbox2
TextBox1.Text = a;
TextBox2.Text = b;
}

Output: Now the output is:


After the Submit button is clicked the value of user name and password is submited to
the server. We cannot restore the value again because after the postback the instance of
the control is destroyed and on clicking of the Restore Button the server takes a new
request and the server cannot restore the value of the TextBox.

Features Of View State

These are the main features of view state:

1. Retains the value of the Control after post-back without using a session.

2. Stores the value of Pages and Control Properties defined in the page.

And now I am explaining the stored value in the View State and the remaining steps are
the same as the previous.

Code: Now write this code:

protected void Button1_Click(object sender, EventArgs e)


{
//Value of Textbox1 and TectBox2 is assigin on the ViewState
ViewState["name"] = TextBox1.Text;
ViewState["password"] = TextBox2.Text;
//after clicking on Button TextBox value Will be Cleared
TextBox1.Text = TextBox2.Text = string.Empty;
}
protected void Button3_Click(object sender, EventArgs e)
{
//If ViewState Value is not Null then Value of View State is Assign to TextBox
if (ViewState["name"] != null)
{
TextBox1.Text = ViewState["name"].ToString();
}
if (ViewState["password"] != null)
{
TextBox2.Text = ViewState["password"].ToString();
}
}

Output: Now the output is:

After clicking on the Submit Button the value of user name and password is submitted in
View State and the View State stores the value of user name and password during post-
back.

After click on the Restore Button we can get the value again. The Value must be
retained during post-back and the values are stored into a base 64 encoded string and
this information is then put into the View State Hidden Field.

Data Objects That Can be stored in View state

1. String

2. Boolean Value

3. Array Object
4. Array List Object

5. Hash Table

6. Custom type Converters

Advantages of View State

1. Easy to Implement.

2. No server resources are required: The View State is contained in a structure


within the page load.

3. Enhanced security features: It can be encoded and compressed or Unicode


implementation.

Disadvantages of View State

1. Security Risk: The Information of View State can be seen in the page output
source directly. You can manually encrypt and decrypt the contents of a Hidden
Field, but It requires extra coding. If security is a concern then consider using a
Server-Based state Mechanism so that no sensitive information is sent to the
client.

2. Performance: Performance is not good if we use a large amount of data because


View State is stored in the page itself and storing a large value can cause the
page to be slow.

3. Device limitation : Mobile Devices might not have the memory capacity to store a
large amount of View State data.

4. It can store values for the same page only.

When We Should Use View State

1. When the data to be stored is small.

2. Try to avoid secure data.


How to Enable and Disable View State

You can enable and disable View State for a single control as well as at the page level
also. To turn off View State for a single control, set the EnableViewState property of that
control to false.

TextBox1.EnableViewState=false;

To turn off the View State for an entire page, we need to set EnableViewState to false of
the page directive as shown below:

<%Page Language="C#" EnableViewState="false";

For enabling the same, you need to use the same property just set it to "True".

View State Security

View State Data is stored in the form of Base 64 encoding but it is not more secure,
anyone can easily break it. So there are the following 2 options:

1. Using the MAC for Computing the View State Hash Value

Generally, the larger MAC key is used to generate a Hash Key. When the key is
auto-generated then ASP.NET uses SHA-1 encoding to create a larger key.
Those keys must be the same for all the server. If the key is not the same and the
page is posted back to a different server than the one that created the page then
the ASP.NET Page Framework raises an exception. We can enable it by using:

<%Page Language="C#" EnableViewState="true" EnableViewStateMac="true";


2. Encryption

By using MAC Encoding we cannot prevent the viewing of the data so to prevent
the viewing, transmit the page over SSL and encrypt the View State Data. To
encrypt the data we have the ViewStateEncryptionMode Property and it has the
following 3 options:

o Always: Encrypt the data Always.

o Never: Encrypt the data Never.

o Auto: Encrypt if any Control request specially for Encryption

We can enable it by using:

<%Page Language="C#" EnableViewState="true ViewStateEncryptionMode="Always"

Server Side View State In ASP.NET

Client-side View State

Step 1

Open the Visual Studio, go to the new project, add a ASP.NET empty web application.
Step 2

Then right-click on the Solution Explorer, add a new item and then add a new web form.
Step 3

Now in theWebForm1.aspx we write the following code.

Code

1. <%@ Page Language="C#" AutoEventWireup="true" CodeBehind


="WebForm1.aspx.cs" Inherits="WebApplication1.WebForm1" %>

2.

3. <!DOCTYPE html>

4.

5. <html xmlns="http://www.w3.org/1999/xhtml">

6. <head runat="server">

7. <title></title>

8. </head>

9. <body>
10. <form id="form1" runat="server">

11. <div>

12. <table>

13. <tr>

14. <td>

15. Name::

16. </td>

17. <td>

18. <asp:TextBox ID="txtname" runat="server"></asp:TextBox>

19. </td>

20. </tr>

21. <tr>

22. <td>

23. father Name::

24. </td>

25. <td>

26. <asp:TextBox ID="txtfathername" runat="server"></asp:TextBox>

27. </td>

28. </tr>

29. <tr>

30. <td>

31. City::

32. </td>

33. <td>

34. <asp:DropDownList ID="DropDownList1" runat="server">

35. <asp:ListItem>--select--</asp:ListItem>

36. <asp:ListItem>Delhi</asp:ListItem>

37. <asp:ListItem>Noida</asp:ListItem>

38. <asp:ListItem>Bareilly</asp:ListItem>
39. <asp:ListItem>Gaziabaad</asp:ListItem>

40. <asp:ListItem></asp:ListItem>

41. </asp:DropDownList>

42. </td>

43. </tr>

44. <tr>

45. <td>

46. Gender::

47. </td>

48. <td>

49. <asp:RadioButtonList ID="RadioButtonList1" runat="server" RepeatDir


ection="Horizontal">

50. <asp:ListItem>Male</asp:ListItem>

51. <asp:ListItem>Female</asp:ListItem>

52. </asp:RadioButtonList>

53. </td>

54. </tr>

55. <tr>

56. <td>

57. <asp:Button ID="btnsubmit" runat="server" Text="Submit" OnClick="b


tnsubmit_Click" />

58. </td>

59. <td>

60. <asp:Button ID="btnrestore" runat="server" Text="Restore" OnClick="


btnrestore_Click" />

61. </td>

62. </tr>

63.

64. </table>

65. </div>
66. </form>

67. </body>

68. </html>

Step 4

Then open your WebForm1.aspx .cs and write the following code.

Code

1. using System;

2.

3. namespace WebApplication1

4. {

5. public partial class WebForm1 : System.Web.UI.Page

6. {

7. public string Name, fatherName, City, Gender;

8. protected void Page_Load(object sender, EventArgs e)

9. {

10.

11. }

12.

13. protected void btnsubmit_Click(object sender, EventArgs e)

14. {

15. ViewState["Name"] = txtname.Text;

16. ViewState ["fatherName"] = txtfathername.Text;

17. ViewState["City"] = DropDownList1.SelectedItem.Text;

18. ViewState["Gender"] = RadioButtonList1.SelectedItem.Text;

19. clear();

20.

21. }

22.
23. protected void btnrestore_Click(object sender, EventArgs e)

24. {

25. if (ViewState["Name"] != null)

26. {

27. txtname.Text = ViewState["Name"].ToString();

28. }

29. if (ViewState["fatherName"] != null)

30. {

31. txtfathername.Text = ViewState["fatherName"].ToString();

32. }

33. if (ViewState["City"] != null)

34. {

35. DropDownList1.SelectedItem.Text = ViewState["City"].ToString();

36. }

37. if (ViewState["Gender"] != null)

38. {

39. RadioButtonList1.SelectedItem.Text = ViewState["Gender"].ToString();

40. }

41. }

42. public void clear()

43. {

44. txtname.Text = "";

45. txtfathername.Text = "";

46. DropDownList1.SelectedItem.Text = "";

47. RadioButtonList1.SelectedItem.Text = "";

48.

49. }

50. }

51. }
This is a simple client-side View State example. First when we click on the submit button
the data goes and is stored in the View State and when we click on the restore button
the data comes from the View State and is shown on the page. When we run the
application we get the following output:

Step 5

Now at that page in the browser where your application is running right-click on it and
click on the view page source. There you will find your View State in encrypted format.

Code

1. <div class="aspNetHidden"><input type="hidden" name="__VIEWSTATE" id="__VIEWSTAT


E" value="8LrMyuvVAZko9eSik2wPrQK4zScyasSQS0fbKWCDypaCaLeSfUQsYSc1d50IbUNqc
Ux1J7DNEW7dGalHzTBjFrGeHVxmwiDzXVgeoAGGWTM8I6JVj0d9+iRcW9HJg3McSfqPq1yNSI
okt2ShPZh8lMmt+mKPIg2MPfAtnixAiaU5bQQkOxp2Pp9ztgljl5lD+Wnz4BqzA6PRylHXMfvGjv
egUcGOLVPPxUTvcCxoXH+XL/Zhkco1BdRaIPXM1Ssh" /></div>

So this is a client-side View State where we preserve the data during the page post-back
method and call that data again and again on a similar page.

Now here we will discuss the Server-side View State.

Server-side View State

As I said above that View State stores the information during the page post-back. It
stores the value of the server controls in a web form. The main advantage of View State
is that it retains the control's values. The main problem with client-side View States is
that when we convert our ASP web site into an ASP.Net web site we get an exception
related to the View State and that exception is "The View State is invalid for this page
and might be corrupted". So what are the reasons for this exception? The reason is that
when the server redirecting is done the end-user sometimes uses the corrupt version of
that page at which his/her View State exists because if there is any change in the hidden
View State value then there will be an exception generated.

The other reason is that many browsers do not support the large hidden field inside it
and sometimes when we make a View State there may be a large hidden file generated
for the View State. So this is another reason to overcome this problem to save the View
State at the server using the session object.

So now I have explained how to make a Server-side View State.

Step 1

For making a server-side View State we first must


override"LoadPageStateFromPersistenceMedium()" and then override
the"SavePageStateToPersistenceMedium" that are the page events. Then we write
the View State code in the database or the file system depending on our needs.

The working of the LoadPageStateFromPersistenceMedium() and the


SavePageStateToPersistenceMedium is totally dependent on the View State size. When
the end user makes a request for the first time to use the page then by default
SavePageStateToPersistenceMedium emerges. The main work of this event to save the
View State, but when the user did not send the request the first time, in other words
when the post-back event is true then the first LoadPageStateFromPersistenceMedium
is generated and then the SavePageStateToPersistenceMedium occurs.

Step 2

Now again open the Visual Studio, go to the new website and add it.

Step 3

Go to the Solution Explorer, right-click on it and add a new Web form. And we also make
a database table by which we bind the data in our grid view. That grid view is used by us
in the following code.

The WebForm2.aspx code

1. <%@ Page Language="C#" AutoEventWireup="true" CodeBehind


="WebForm2.aspx.cs" Inherits="WebApplication1.WebForm2" %>

2.

3. <!DOCTYPE html>

4.

5. <html xmlns="http://www.w3.org/1999/xhtml">

6. <head runat="server">

7. <title></title>

8. </head>
9. <body>

10. <form id="form1" runat="server">

11. <div>

12. </div>

13. <asp:TextBox ID="TextBox1" runat="server"></asp:TextBox>

14. <br />

15. <br />

16. <br />

17. <asp:Button ID="Button1" runat="server" Text="GetState" />

18. <br />

19. <asp:GridView ID="GridView1" runat="server" AllowPaging="True" AllowSor


ting="True" AutoGenerateColumns="False" DataSourceID="SqlDataSource1">

20. <Columns>

21. <asp:BoundField DataField="Name" HeaderText="Name" SortExpressio


n="Name" />

22. <asp:BoundField DataField="FatherName" HeaderText="FatherName"


SortExpression="FatherName" />

23. <asp:BoundField DataField="rollno" HeaderText="rollno" SortExpressi


on="rollno" />

24. <asp:BoundField DataField="designation" HeaderText="designation" S


ortExpression="designation" />

25. </Columns>

26. </asp:GridView>

27. <asp:SqlDataSource ID="SqlDataSource1" runat="server" ConnectionString


="<%$ ConnectionStrings:rizzuConnectionString %>" SelectCommand="SELECT *
FROM [rizwan]"></asp:SqlDataSource>

28. </form>

29. </body>

30. </html>

Step 4

Then we write the code in the following.

WebForm2.aspx.cs file Code


1. using System;

2. using System.Web.UI;

3. using System.IO;

4.

5. namespace WebApplication1

6. {

7. public partial class WebForm2 : System.Web.UI.Page

8. {

9. protected void Page_Load(object sender, EventArgs e)

10. {

11.

12. }

13.

14. protected override void SavePageStateToPersistenceMedium(object state)

15. {

16.

17. string file = GenerateFileName();

18.

19. FileStream filestream = new FileStream(file, FileMode.Create);

20.

21. LosFormatter formator = new LosFormatter();

22.

23. formator.Serialize(filestream, state);

24.

25. filestream.Flush();

26.

27. filestream.Close();

28.

29. filestream = null;


30.

31. }

32.

33. protected override object LoadPageStateFromPersistenceMedium()

34. {

35.

36. object state = null;

37.

38. StreamReader reader = new StreamReader(GenerateFileName());

39.

40. LosFormatter formator = new LosFormatter();

41.

42. state = formator.Deserialize(reader);

43.

44. reader.Close();

45.

46. return state;

47.

48. }

49.

50. private string GenerateFileName()

51. {

52.

53. string file = Session.SessionID.ToString() + ".txt";

54.

55. file = Path.Combine(Server.MapPath("~/ViewStateFiles") + "/" + file);

56.

57. return file;

58.
59. }

60.

61. }

62. }

Now when we run the application we will see it in the browser like this.

And now here our View State is stored in the ViewStateFiles folder that are present in
our application. Here our View State code is like the following:

1. /
wEPGAEFCUdyaWRWaWV3MQ88KwAMAQgCAWQPBQoxNDE4NjIwMDUzD2QWAgID
D2QWAgIFDzwrABEDAA8WBB4LXyFEYXRhQm91bmRnHgtfIUl0ZW1Db3VudAIDZAE
QFgAWABYADBQrAAAWAmYPZBYKAgEPZBYIZg8PFgIeBFRleHQFBlJpendhbmRkAgE
PDxYCHwIFBXNhaGlsZGQCAg8PFgIfAgUHVENBMTEwMmRkAgMPDxYCHwIFB01hb
mFnZXJkZAICD2QWCGYPDxYCHwIFBFNhYWRkZAIBDw8WAh8CBQVzYW1hcmRkAg
IPDxYCHwIFB1RDQTExMDhkZAIDDw8WAh8CBQZIZWxwZXJkZAIDD2QWCGYPDxYC
HwIFBFJhdmlkZAIBDw8WAh8CBQZyYW1lc2hkZAICDw8WAh8CBQhUQ0ExMTA4OW
RkAgMPDxYCHwIFC2NvYXJkaW5hdG9yZGQCBA8PFgIeB1Zpc2libGVoZGQCBQ8PFg
IfA2hkZA==

Now when you right-click on the running page there is no hidden field for View State.
Then another method makes a server-side View State. To see it Click here to know.

Advantages of server-side View State

The main advantage is that if a browser does not support a large encrypted file that is
generated by the client-side View State then by the client-side View State we can handle
it. As we know sometimes when we open an ASP web site in ASP.NET there will be
some time corruption problem so it also minimizes the corruption problem. It also
converts large client-side pages into a small client-side page because the View State
data is stored at the server.

Disadvantages of Server-side View State

The main draw back is that the developer does not know how much space is taken by a
View State on the server. If it takes a very large space there will be a problem. Another
disadvantage is that server-side View State uses the server memory for the session
object.

ViewState for TextBox in ASP.Net

Step 1

Open Visual Studio and create a webpage. Drag and drop one TextBox and one button
control to that page.

1. <div>

2. Name<asp:TextBox ID="TextBox1" runat="server"></asp:TextBox>

3. <br />

4. <asp:Button ID="btnSubmit" runat="server"

5. Text="Submit" />

6. </div>

Step 2

Right-click on the TextBox and select EnableViewState to false and


ViewStateMode="Disabled" for TextBox.

Then the HTML of the TextBox will be like:


1. Name<asp:TextBox ID="TextBox1" runat="server"

2. EnableViewState="False" ViewStateMode="Disabled"

3. ></asp:TextBox>

Step 3

Run the page. Then enter some value inside the TextBox and click on the button to
submit the page.

Now notice that we are not losing the data, even if the ViewState is disabled for the
TextBox. Now a big question arises.

Where the data for the TextBox is coming from when EnableViewState is False

When EnableViewState is false the data for the TextBox is coming from
theSystem.Web.UI.WebControls.TextBox class, that is one of several classes that
implement theIPostBackDataHandler interface. This interface requires
the LoadPostData method. After page initialization is completed but before the Load
event loading of ViewState data is invoked (LoadViewState), then if the control
implements IPostBackDataHandler, the loading of the form data is invoked
(LoadPostData). The Text property of a TextBox control can therefore be set even if the
View State mechanism is disabled.

Completely disable the View State mechanism for TextBox controls and the like

The View State mechanism for TextBox controls and the like cannot be completely
disabled. For example, View State is useful when the TextChanged event is handled (for
comparing the current and previous values). It can also be used when the value that is
being set is other than the one related to the Control's value (for example ForeColor,
FontSize and so on).

All controls that implement IPostBackDataHandler load their values even if ViewState
is off.

Here's a list of controls that implement IPostBackDataHandler:

CheckBox
CheckBoxList

DropDownList

ListBox

RadioButtonList

TextBox

The use of ViewState for the TextBox

The ViewState is not only used for maintaining the state of data inside a control, there
are also many other state management that has been done for ViewState for a control
like ForeColor, BackColor and so on. Now take a close look at following example in
which I am setting the background and forground color of the TextBox when the user
selects the Radio buttons.

First design the web form like the following.

1. <table class="style1">

2. <tr>

3. <td>

4. BackColor

5. </td>

6. <td>

7.

8. <asp:RadioButtonList ID="rbLBackColor" runat="server" AutoPostBack="True"

9. onselectedindexchanged="rbLBackColor_SelectedIndexChanged"

10. RepeatDirection="Horizontal">

11. <asp:ListItem>Red</asp:ListItem>

12. <asp:ListItem>Green</asp:ListItem>

13. <asp:ListItem>Blue</asp:ListItem>

14. </asp:RadioButtonList>

15. </td>

16. </tr>
17. <tr>

18. <td>

19. ForeColor

20. </td>

21. <td>

22.

23. <asp:RadioButtonList ID="rbLForeColor" runat="server" AutoPostBack="True"

24. onselectedindexchanged="rbLForeColor_SelectedIndexChanged"

25. RepeatDirection="Horizontal">

26. <asp:ListItem>Red</asp:ListItem>

27. <asp:ListItem>Green</asp:ListItem>

28. <asp:ListItem>Blue</asp:ListItem>

29. </asp:RadioButtonList>

30. </td>

31. </tr>

32. <tr>

33. <td>

34. Name

35. </td>

36. <td>

37. <asp:TextBox ID="TextBox1" runat="server" EnableViewState="False"

38. ViewStateMode="Disabled"></asp:TextBox>

39. </td>

40. </tr>

41. <tr>

42. <td>

43.

44. </td>
45. <td>

46. <asp:Button ID="btnSubmit" runat="server" Text="Submit" EnableViewState=


"False" OnClick="btnSubmit_Click" />

47. </td>

48. </tr>

49. </table>

Keep in mind that you use EnableViewState="False" ViewStateMode="Disabled" for


TextBox.

Now double-click the radio button list to generate the event handler for that and write the
following code for each radioButtonList.

1. protected void rbLBackColor_SelectedIndexChanged(object sender, EventArgs e)

2. {

3. if(rbLBackColor.SelectedItem.Value.Equals("Red"))

4. {

5. TextBox1.BackColor =Color.Red ;

6. }

7. else if(rbLBackColor.SelectedItem.Value.Equals("Green"))

8. {

9. TextBox1.BackColor = Color.Green;

10. }

11. else if(rbLBackColor.SelectedItem.Value.Equals("Blue"))

12. {

13. TextBox1.BackColor = Color.Blue;

14. }

15. }

16.

17. protected void rbLForeColor_SelectedIndexChanged(object sender, EventArgs e)

18. {

19. if (rbLForeColor.SelectedItem.Value.Equals("Red"))
20. {

21. TextBox1.ForeColor = Color.Red;

22. }

23. else if (rbLForeColor.SelectedItem.Value.Equals("Green"))

24. {

25. TextBox1.ForeColor = Color.Green;

26. }

27. else if (rbLForeColor.SelectedItem.Value.Equals("Blue"))

28. {

29. TextBox1.ForeColor = Color.Blue;

30. }

31. }

Now run the page and you will get the following output.

Now select each radio button to get the change in the color of the TextBox like:

Until then everything is normal. Now click the button and you will notice that the TextBox
ForeColor and BackColor state we are losing after postback. So here viewState comes
into the picture. If we enable view true for the TextBox like:
1. <asp:TextBox ID="TextBox1" runat="server" ></asp:TextBox>

Now if we click the button even if after a postback then the Forecolor and BackColor
state for that TextBox will be the same as the selected Radio Buttons.

This is small but tricky things for view state in ASP.NET control.