Documentos de Académico
Documentos de Profesional
Documentos de Cultura
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.
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:
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:
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.
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 2 : Then click on "New Project" > "Web" > "ASP.NET Empty Web Application" .
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:
Step 7 : Now to count the number of users online we need to use the global.asax file as
in the following:
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. }
7. {
9. Application.Lock();
11. Application.UnLock();
12. }
14. {
16. Application.Lock();
18. Application.UnLock();
19. }
Step 8 : Now to show the online users we need to use a web form as in the following:
2. {
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.
1. Application State variables are available across all pages and all sessions.
Application State variables are like multi-user Global data.
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.
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?
Application["LoginID"] = "annathurai";
Application["DomainName"] = "www.annathurai.com";
}
We can retrieve all application variable on the currently running application's keys by
using HttpApplicationState class.
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:
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.
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.
Global.asax Code
2. <script runat="server">
4. {
6. Application["VisitorCount"] = 0;
7. }
9. {
11. }
13. {
15. }
17. {
20. }
22. {
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
27. }
28. </script>
Figure 2: Code
As the session starts we set the visitor count to +1 in the event of the 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.
4. xmlns="http://www.w3.org/1999/xhtml">
5. <head runat="server">
6. <title></title>
7. <style type="text/css">
8. .style1
9. {
11. }
12. .style2
13. {
15. }
16. </style>
17. </head>
21. <strong>
25. </span>
26. </strong>
34. </div>
35. <p>
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.
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;
HttpCookie myCookie;
myCookie.Expires = DateTime.Now.AddHours(1);
Response.Cookies.Add(myCookie);
Response.Redirect("Default2.aspx");
}
}
Output 1:
Code for Default2.aspx 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;
Response.Write("________________________________________________" + "<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
Cookies in ASP.NET
Type of Cookies?
1. Persist Cookie - A cookie has not have expired time Which is called as Persist
Cookie
Its really easy to create a cookie in the Asp.Net with help of Response object or
HttpCookie
Example 1:
Example 2:
Response.Cookies["userName"].Value = "Annathurai";
Response.Cookies["userColor"].Value = "Black";
Its easy way to retrieve cookie value form cookes by help of Request object.
Example 1:
Example 2:
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.
5. Expires => Which is used to set expire date for the cookies.
Advantages of Cookie:
4. Fast accessing.
Disadvantages of Cookie
2. No security.
In this example you use the textbox value in other page without cookie in javascript.
</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>
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;
}
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
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;
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.
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.
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.
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.
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:
2.
4. <html xmlns="http://www.w3.org/1999/xhtml">
6. <title></title>
7. <style type="text/css">
8. .style1
9. {
11. }
12. .style2
13. {
14. width: 179px;
15. }
16. </style>
17. </head>
18. <body>
20. <div>
22. <tr>
25. </td>
26. <td>
27.
28. </td>
29. </tr>
30. <tr>
33. </td>
34. <td>
36. </td>
37. </tr>
38. <tr>
40. Password
41. </td>
42. <td>
43. <asp:TextBox ID="tbPwd" runat="server"></asp:TextBox>
44. </td>
45. </tr>
46. <tr>
49. </td>
50. <td>
51.
52. </td>
53. </tr>
54. </table>
55. </div>
56. </form>
57. </body>
58. </html>
2. {
3.
//create a cookie by using HttpCookie class and add the name of the cookie that is Democo
okie
6. cookie["UserName"] = tbUserName.Text;
7. cookie["Pwd"] = tbPwd.Text;
9. Response.Cookies.Add(cookie);
12. }
Step 6: Now the WebForm2.aspx Web Form is also added and after the following Code
is:
2.
4. <html xmlns="http://www.w3.org/1999/xhtml">
6. <title></title>
7. <style type="text/css">
8. .style1
9. {
11. }
12. .style2
13. {
16. </style>
17. </head>
18. <body>
20. <div>
22. <tr>
25. </td>
26. <td>
27.
28. </td>
29. </tr>
30. <tr>
33. </td>
34. <td>
36. </td>
37. </tr>
38. <tr>
40. Password
41. </td>
42. <td>
44. </td>
45. </tr>
46. <tr>
48.
49. </td>
50. <td>
51.
52. </td>
53. </tr>
54. </table>
55. </div>
56. </form>
57. </body>
58. </html>
2. {
5. if (cookie != null)
6. {
8. lblUname.Text = cookie["UserName"];
9. LblPwd.Text = cookie["Pwd"];
10. }
11. }
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.
2. {
3.
//create a cookie by using HttpCookie class and add the name of the cookie that is Democo
okie
6. cookie["UserName"] = tbUserName.Text;
7. cookie["Pwd"] = tbPwd.Text;
9. Response.Cookies.Add(cookie);
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.
2. {
3. //Write Cookie
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. }
2. {
5. if (cookie != null)
6. {
7. lblUname.Text=Request.Cookies["userinfo"]["UserName"];
8. LblPwd.Text=Request.Cookies["userinfo"]["Pwd"];
9. }
10. }
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";
1. Domain: Using these properties we can set the domain of the cookie.
The following describes how to check whether or not the browser accepts cookies.
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. {
8. if (Request.QueryString["cookie"] == null)
9. {
13. Response.Cookies.Add(cookie);
15. Response.Redirect("Default.aspx?cookie=1");
16. }
17. else
18. {
24. {
26. }
27. }
28. }
29. else
30. {
32. }
33. }
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.
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
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. {
11. {
13. {
15. {
19. {
21. }
22. }
23.
24. }
25.
27. {
28. if(CheckBox1.Checked==true)
29. {
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).
1. Go to Settings:
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 2: Then click on "New Project" > "Web" >"ASP.NET Empty Web Application".
//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;
}
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.
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.
1. String
2. Boolean Value
3. Array Object
4. Array List Object
5. Hash Table
1. Easy to Implement.
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.
3. Device limitation : Mobile Devices might not have the memory capacity to store a
large amount of View State data.
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:
For enabling the same, you need to use the same property just set it to "True".
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:
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:
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
Code
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>
19. </td>
20. </tr>
21. <tr>
22. <td>
24. </td>
25. <td>
27. </td>
28. </tr>
29. <tr>
30. <td>
31. City::
32. </td>
33. <td>
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>
50. <asp:ListItem>Male</asp:ListItem>
51. <asp:ListItem>Female</asp:ListItem>
52. </asp:RadioButtonList>
53. </td>
54. </tr>
55. <tr>
56. <td>
58. </td>
59. <td>
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. {
6. {
9. {
10.
11. }
12.
14. {
19. clear();
20.
21. }
22.
23. protected void btnrestore_Click(object sender, EventArgs e)
24. {
26. {
28. }
30. {
32. }
34. {
36. }
38. {
40. }
41. }
43. {
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
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.
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.
Step 1
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.
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>
11. <div>
12. </div>
20. <Columns>
25. </Columns>
26. </asp:GridView>
28. </form>
29. </body>
30. </html>
Step 4
2. using System.Web.UI;
3. using System.IO;
4.
5. namespace WebApplication1
6. {
8. {
10. {
11.
12. }
13.
15. {
16.
18.
20.
22.
24.
25. filestream.Flush();
26.
27. filestream.Close();
28.
31. }
32.
34. {
35.
37.
39.
41.
43.
44. reader.Close();
45.
47.
48. }
49.
51. {
52.
54.
56.
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.
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.
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.
Step 1
Open Visual Studio and create a webpage. Drag and drop one TextBox and one button
control to that page.
1. <div>
3. <br />
5. Text="Submit" />
6. </div>
Step 2
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.
CheckBox
CheckBoxList
DropDownList
ListBox
RadioButtonList
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.
1. <table class="style1">
2. <tr>
3. <td>
4. BackColor
5. </td>
6. <td>
7.
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.
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>
38. ViewStateMode="Disabled"></asp:TextBox>
39. </td>
40. </tr>
41. <tr>
42. <td>
43.
44. </td>
45. <td>
47. </td>
48. </tr>
49. </table>
Now double-click the radio button list to generate the event handler for that and write the
following code for each radioButtonList.
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. }
12. {
14. }
15. }
16.
18. {
19. if (rbLForeColor.SelectedItem.Value.Equals("Red"))
20. {
22. }
24. {
26. }
28. {
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.