Download presentation
Presentation is loading. Please wait.
Published byStella Barton Modified over 6 years ago
1
Internet Programming Chapter 9: State Management in ASP.NET
Web pages are, by definition, stateless. This means that as you move from web page to web page, the data from each page is automatically discarded. Because you might need data from one of these previous pages, you need to store that data (or state) as you move from one page to another. To overcome this inherent limitation of losing state, automatic state management facilities should be provided. The "state" can be stored either on the client or on the server.
2
State Management State management is the process by which you maintain states and page information over multiple requests for the same or different pages. ASP.NET provides multiple ways to maintain states between server round trips. Choosing among the options for state management available in ASP.NET will depend heavily upon your application, and it should be based on the following criteria: How much information do you need to store? Do you want to store the information on the client or server? Does the client accept cookies? Is the information sensitive (such as passwords)? What sorts of performance criteria do you have for your application?
3
State Management in ASP.NET
ASP.NET supports various client-side and server-side options for state management. Client-side options are: The ViewState property Hidden form fields Cookies Query strings Server-side options are: Application state Session state
4
State Management on Client and Server
5
ViewState Without some means of preserving the state between round trips to the Web server, data that you’ve entered onto a Web page would disappear as you postback a page. If you click a button that causes a postback to the server, without some help from ASP.NET, your data would be lost as the server resends the current page. ASP.NET takes care of managing this round-trip postback state (with attribute runat="server" in the form) for you with no extra coding on your part. ASP.NET keeps track of this data by adding a hidden input control on each page. This control (always named __VIEWSTATE) maintains all the information from all the controls on the page that have their EnableViewState property set to True. You can see this hidden input variable if you view the source for a Web page from your browser.
6
How ViewState Works When the WebForm's HTML output is streamed to the browser, the hidden "__VIEWSTATE" field is added to the form. When the form is posted back to the server, the Request.Form Collection contains the field values of the posted form. The server reads the form POST data, extracts the values, and updates (rewrites) the ViewState value to be sent back to the client.
7
How ViewState Works
8
ViewState So now in ASP.NET the server retains the information about the previous client request, such as the form field values. So when the page is sent back to the server the web processor reads the hidden _ViewState value and restores it in the server controls. Example: Page Language="C#" %> <html> <body> <form runat="server"> <asp:TextBox id="txtName" runat="server" /> <asp:Button id="btnSubmit" Text="Click Me" runat="server" /> </form> </body> </html> If you do not want to use view state, you can turn it off: Page EnableViewState="False" %> hidden field
9
Hidden Form Fields ASP.NET allows you to use HTML-standard hidden fields in a form. A hidden field is not visible in the browser, but you can set its properties just as you can with a standard control. When a page is submitted to the server, the content of a hidden field is sent in the HTTP Form collection along with the values of other controls. A hidden field acts as a repository for any page-specific information that you would like to store directly in the page. A hidden field stores a single variable in its value property and must be explicitly added to the page. Then you insert your value into the hidden field.
10
Hidden Form Fields Hidden input fields can be used to pass data from one page to another. When the user clicks on a Submit button, the form posts the data the user filled in, along with any hidden input fields as well. Create a hidden input field using a normal HTML tag, like this: <input type="hidden" value="10" name="txtRate"> You can store data in a hidden input field to help maintain state from one page to another. In the example above, the value 10 is stored in the hidden field named txtRate.
11
Example The example demonstrates how to have several pages that are forms yet after all pages are filled out the final form has access to all inputs. surveypage1.aspx <html><head> <title>surveypage1.aspx</title> </head> <body bgcolor="#FFFFFF"> <form action="surveypage2.aspx" method="post"> First Name<br /> <input type="text" name="first" size="20"> <br /> Last Name<br> <input type="text" name="last" size="20"> <p> <input type="submit" value="Next Question ->"> </p> </form> </body></html>
12
Example surveypage2.aspx <html><head>
<title>surveypage2.aspx</title> </head> <body bgcolor="#FFFFFF"> <form action="surveyresponse.aspx" method="post"> <% first=request.form["first"]; last=request.form["last"]; %> Hair Color<br /> <input type="text" name="haircolor" size="20"><br /> Favorite Color<br /> <input type="text" name="favoritecolor" size="20"> <p> <input type="hidden" name="first" value="<%=first%>"> <input type="hidden" name="last" value="<%=last%>"> <input type="submit" value="Next Question ->"></p> </form> </body></html>
13
Example <html><head>
<title>surveyrespond.aspx</title> </head> <body bgcolor="#FFFFFF"> <% first=request.form["first"]; last=request.form["last"]; haircolor=request.form["haircolor"]; favoritecolor=request.form["favoritecolor"]; %> Thanks for all your information <br /> We are happy to meet you <%=first%> <%=last%> We know your hair color is <%=haircolor%> and your favorite color is <%=favoritecolor%> </body></html>
14
Cookie A cookie is a small amount of data stored either in a text file on the client's file system or in-memory in the client browser session. It contains page-specific information the server sends to the client along with page output. Cookies can be temporary (with specific expiration times and dates) or persistent. You can use cookies to store information about a particular client, session, or application. The cookies are saved on the client device, when the browser requests a page, it sends the information in the cookie along with the request information. The server can read the cookie and extract its value. A typical use is to store a token (perhaps encrypted) indicating that the user has already been authenticated in your application. The browser can only send the data back to the server that originally created the cookie. Therefore, cookies are a relatively secure way of maintaining user-specific data.
15
Cookie Operations -- Server Write to Client
Write cookie to client: // The current time DateTime now = DateTime.Now; // Declare and initialize a cookie object HttpCookie c = new HttpCookie("Info"); // Set the cookie c.Value = TextBox1.Text; c.Expires = now.AddHours(1); // Write the cookie back to the client browser Response.Cookies.Add(c);
16
Cookie Operations -- Server Read From Client
Read from a cookie: // Get the cookie object HttpCookie c = Request.Cookies["info"]; // if there is the cookie object if (c != null) { // read the value of the cookie TextBox1.Text = c.Value.ToString();
17
Query Strings A query string is a string (?xx = yy) appended to the end of a page's URL. For example: In the URL path above, the query string starts with the question mark (?) and includes two attribute-value pairs, one called "category" and the other called "price." Query strings provide a simple but limited way of maintaining some state information. For example, they are an easy way to pass information from one page to another, such as passing a product number from one page to another page where it will be processed.
18
Query Strings However, most browsers and client devices impose a 255-character limit on the length of the URL. In addition, the query values are exposed to the Internet via the URL so in some cases security may be an issue. In order for query string values to be available during page processing, you must submit the page using an HTTP GET method. That is, you cannot take advantage of a query string if a page is processed in response to an HTTP POST method.
19
Application of Query String
For passing variables content between pages ASP.NET gives us several choices, we can use QueryString property of Request Object. For the URL below: In this address you send 3 information: wf.aspx, this is the page your browser will go. name=Peter, you send a name variable which is set to Peter lastName=Chan, you send a lastName variable which is set to Chan
20
Application of Query String
Suppose we have a form with 2 textboxes and one submit button. When the button is clicked, we will redirect to the above URL. We may put the following code to the submit button event handler. private void btnSubmit_Click(object s, System.EventArgs e){ Response.Redirect("wf.aspx?Name=" + this.txtName.Text + "&LastName=" + this.txtLastName.Text); } Now how to retrieve this values from second page. Put this code to second page private void Page_Load(object sender, System.EventArgs e) { this.txtBox1.Text = Request.QueryString["Name"]; this.txtBox2.Text = Request.QueryString["LastName"];
21
Application State ASP.NET allows you to save values using application state (an object instance of the HttpApplicationState class) for each active Web application. Application state is a global storage mechanism accessible from all pages in the Web application and is thus useful for storing information that needs to be maintained between server round trips and between pages. Application state is a key-value structure created during each request to a specific URL. You can add your application-specific information to this structure to store it between page requests. Once you add your application-specific information to application state, the server manages it.
22
Example on Application Object
Initialize the Application in Global.asax: <script language="C#" runat="server"> void Application_OnStart() { Application["example"] = 0; } </script>
23
Example on Application Object
On the server example.aspx: Page language="c#"%> <script language="C#" runat="server"> private void Page_Load(object sender, EventArgs e) { Application.Lock(); Application["example"]=(int)Application["example"]+1; Application.UnLock(); //Output Application Response.Write(Application["example"]); } </script> <html> <body> </body></html>
24
Example on Application Object
The example.aspx can be tested by calling the web form in different web browsers. The result is: Application object can be accessed in different browsers and the value will be increment in different browsers.
25
Session State ASP.NET allows you to save values using session state, which is an instance of the HttpSessionState class for each active Web application session. Session state is similar to application state, except that it is scoped to the current browser session. If different users are using your application, each will have a different session state. In addition, if the same user leaves your application and then returns later, that user will also have a different session state. Session state is structured as a key-value structure for storing session-specific information that needs to be maintained between server round trips and between requests for pages.
26
Session state enables you to:
Uniquely identify browser requests and map them to an individual session instance on the server. Store session-specific data on the server for use across multiple browser or client-device requests within the same session. Raise appropriate session management events. In addition, you can write application code leveraging these events. Once you add your application-specific information to session state, the server manages this object.
27
Different Clients Have Different Sessions
ASP.NET Server Client 1 Session of client 1 Client 2 Session of client 2 Client 3 Session of client 3
28
Operations of Sessions
Setting a session variable: Session["key"] = "value"; Printing a session variable's contents: Response.write(Session["key"]); Setting a session variable's contents to another variable: String newvar=(String)Session["key"];
Similar presentations
© 2025 SlidePlayer.com. Inc.
All rights reserved.