A new instance of the Web page class is created each time the page is posted to the server. In traditional Web programming, this would typically mean that all information associated with the page and the controls on the page would be lost with each round trip. For example, if a user enters information into a text box, that information would be lost in the round trip from the browser or client device to the server.
ASP.NET provides multiple ways to maintain state between server round trips. Which of these options you choose depends heavily upon your application, and it should be based on the following criteria:
- How much information do you need to store?
- Does the client accept persistent or in-memory cookies?
- Do you want to store the information on the client or on the server?
- Is the information sensitive?
- What performance and bandwidth criteria do you have for your application?
- What are the capabilities of the browsers and devices that you are targeting?
- Do you need to store information per user?
- How long do you need to store the information?
- Do you have a Web form (multiple servers), a Web garden (multiple processes on one machine), or a single process that serves the application?
To overcome this inherent limitation of traditional Web programming, ASP.NET includes several options that help you preserve data on both a per-page basis and an application-wide basis. These features are as follows:
1. View state
2. Control state
3. Hidden fields
5. Query strings
6. Application state
7. Session state
8. Profile Properties
9. Data Support
View state, control state, hidden fields, cookies, and query strings all involve storing data on the client in various ways. However, application state, session state, profile and data support properties all store data in memory on the server. Each option has distinct advantages and disadvantages, depending on the scenario.
Client Side State Management
The following sections describe options for state management that involve storing information either in the page or on the client computer. For these options, no information is maintained on the server between round trips.
The View State property provides a dictionary object for retaining values between multiple requests for the same page. This is the default method that the page uses to preserve page and control property values between round trips.
When the page is processed, the current state of the page and controls is hashed into a string and saved in the page as a hidden field, or multiple hidden fields if the amount of data stored in the View State property exceeds the specified value in the MaxPageStateFieldLength property. When the page is posted back to the server, the page parses the view-state string at page initialization and restores property information in the page.
Advantages of using view state are:
- No server resources are required - The View state is contained in a structure within the page code.
- Simple implementation - View State does not require any custom programming to use. It is on by default to maintain state data on controls.
- Enhanced security features - The values in view state are hashed, compressed, and encoded for Unicode implementation, which provides more security than using hidden fields.
Disadvantages of using view state are:
- Performance considerations- Because the view state is stored in the page itself, storing large values can cause the page to slow down when users display it and when they post it. This is especially relevant for mobile devices, where bandwidth is often a limitation.
- Device limitations- Mobile devices might not have the memory capacity to store a large amount of view-state data.
- Potential security risks - The view state is stored in one or more hidden fields on the page. Although view state stores data in a hashed format, it can still be tampered with. The information in the hidden field can be seen if the page output source is viewed directly, creating a potential security issue. Control State
ViewState can be disabled for a single control, for an entire page or for an entire web application.
The syntax is:
· Disable ViewState for control (Datagrid in this example)
< asp:datagrid EnableViewState="false" ... / >
· Disable ViewState for a page, using Page directive
< %@ Page EnableViewState="False" ... % >
· Disable ViewState for application through entry in web.config
< Pages EnableViewState="false" ... / >
Create ViewState manually …..
Step1:- Make a webpage as below page format
Step2:- Write some code on button click event
protected void Page_Load(object sender, EventArgs e)
//Get values from View-State
if (ViewState["ViewName"] != null && ViewState["ViewEmail"] != null && ViewState["ViewContact"] != null)
txtName.Text = ViewState["ViewName"].ToString();
txtEmail.Text = ViewState["ViewEmail"].ToString();
txtContact.Text = ViewState["ViewContact"].ToString();
protected void Button1_Click(object sender, EventArgs e)
//Set values in View_State
ViewState["ViewName"] = txtName.Text.Trim();
ViewState["ViewEmail"] = txtEmail.Text.Trim();
ViewState["ViewContact"] = txtContact.Text.Trim();
Sometimes you need to store control-state data in order for a control to work properly. For example, if you have written a custom control that has different tabs that show different information, in order for that control to work as expected, the control needs to know which tab is selected between round trips. The ViewState property can be used for this purpose, but view state can be turned off at a page level by developers, effectively breaking your control. To solve this, the ASP.NET page framework exposes a feature in ASP.NET called control state.
The Control-State property allows you to persist property information that is specific to a control and cannot be turned off like the ViewState property.
Advantages of using control state are:
- No server resources are required- By default, control state is stored in hidden fields on the page.
- Reliability- Because control state cannot be turned off like view state, control state is a more reliable method for managing the state of controls.
- Versatility- Custom adapters can be written to control how and where control-state data is stored.
Disadvantage of using control state are:
- Some programming is required- While the ASP.NET page framework provides a foundation for control state, control state is a custom state-persistence mechanism. To fully utilize control state, you must write code to save and load control state.
Example: The following code example demonstrates how a class that derives from the PageStatePersister class initializes the ControlState property. In this example, the ControlState property has been assigned to the Second field of a Pair object, and serialized using the ObjectStateFormatter class. When the Load method is called, the ObjectStateFormatter class is used to desterilize view state and control state information, and the ControlState property is initialized from the resulting Pair object's Second field.
// Load ViewState and ControlState.
public override void Load()
Stream stateStream = GetSecureStream();
// Read the state string, using the StateFormatter. StreamReader reader = new StreamReader(stateStream);
IStateFormatter formatter = this.StateFormatter;
string fileContents = reader.ReadToEnd();
// Deserilize returns the Pair object that is serialized in
// the Save method.
Pair statePair = (Pair)formatter.Deserialize(fileContents);
ViewState = statePair.First;
ControlState = statePair.Second;
ASP.NET allows you to store information in a Hidden-Field control, which renders as a standard HTML hidden field. A hidden field does not render visibly 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 want to store directly in the page.
It is easy for a malicious user to see and modify the contents of a hidden field. Do not store any information in a hidden field that is sensitive or that your application relies on to work properly.
A Hidden-Field control stores a single variable in its Value property and must be explicitly added to the page. In order for hidden-field values to be available during page processing, you must submit the page using an HTTP POST command. If you use hidden fields and a page is processed in response to a link or an HTTP GET command, the hidden fields will not be available.
Advantages of using hidden fields are:
- No server resources are required- The hidden field is stored and read from the page.
- Widespread support- Almost all browsers and client devices support forms with hidden fields.
- Simple implementation- Hidden fields are standard HTML controls that require no complex programming logic.
Disadvantages of using hidden fields are:
· Potential security risks- The hidden field can be tampered with. The information in the hidden field can be seen if the page output source is viewed directly, creating a potential security issue. You can manually encrypt and decrypt the contents of a hidden field, but doing so requires extra coding and overhead. If security is a concern, consider using a server-based state mechanism so that no sensitive information is sent to the client.
· Simple storage architecture- The hidden field does not support rich data types. Hidden fields offer a single string value field in which to place information. To store multiple values, you must implement delimited strings and the code to parse those strings. You can manually serialize and de-serialize rich data types to and from hidden fields, respectively. However, it requires extra code to do so. If you need to store rich data types on the client, consider using view state instead. View state has serialization built-in, and it stores data in hidden fields.
· Performance considerations- Because hidden fields are stored in the page itself, storing large values can cause the page to slow down when users display it and when they post it.
· Storage limitations- If the amount of data in a hidden field becomes very large, some proxies and firewalls will prevent access to the page that contains them. Because the maximum amount can vary with different firewall and proxy implementations, large hidden fields can be sporadically problematic. If you need to store many items of data, consider doing one of the following:
o Put each item in a separate hidden field.
o Use view state with view-state chunking turned on, which automatically separates data into multiple hidden fields.
o Instead of storing data on the client, persist the data on the server. The more data you send to the client, the slower the apparent response time of your application will be because the browser will need to download or send more data.
Example: Creating Headed Field in ASP.Net
<asp:HiddenField ID="HiddenField1" runat="Server" Value="This is the Value of Hidden field"/>
<asp:Button ID="Button1" runat="Server" OnClick="ChangeLabelText" Text="Change Label Text to Hiidden Field Value"/>
//Fires when Button is clicked protected void ChangeLabelText(object sender, EventArgs e)
A cookie is a small amount of data that is stored either in a text file on the client file system or in-memory in the client browser session. It contains site-specific information that the server sends to the client along with page output. Cookies can be temporary (with specific expiration times and dates) or persistent.
The browser can only send the data back to the server that originally created the cookie. However, malicious users have ways to access cookies and read their contents. It is recommended that you do not store sensitive information, such as a
user name or password, in a cookie. Instead, store a token in the cookie that identifies the user, and then use the token to look up the sensitive information on the server.
Advantages of using cookies are:
· Configurable expiration rules- The cookie can expire when the browser session ends, or it can exist indefinitely on the client computer, subject to the expiration rules on the client.
· No server resources are required- The cookie is stored on the client and read by the server after a post.
· Simplicity- The cookie is a lightweight, text-based structure with simple key-value pairs.
· Data persistence- Although the durability of the cookie on a client computer is subject to cookie expiration processes on the client and user intervention, cookies are generally the most durable form of data persistence on the client.
Disadvantages of using cookies are:
· Size limitations- Most browsers place a 4096-byte limit on the size of a cookie, although support for 8192-byte cookies is becoming more common in newer browser and client-device versions.
· User-configured refusal- Some users disable their browser or client device's ability to receive cookies, thereby limiting this functionality.
· Potential security risks- Cookies are subject to tampering. Users can manipulate cookies on their computer, which can potentially cause a security risk or cause the application that is dependent on the cookie to fail. Also, although
cookies are only accessible by the domain that sent them to the client, hackers have historically found ways to access cookies from other domains on a user's computer. You can manually encrypt and decrypt cookies, but it requires extra
coding and can affect application performance because of the time that is required for encryption and decryption.
Example:- Set and Get values in Cookies
//Set the values
A Query String is information that is appended to the end of a page URL. A typical Query String might look like the following example:
In the URL path above, the query string starts with a question mark (?) and includes two attribute/value pairs, one called "category" and the other called "price."
Query strings provide a simple but limited way to maintain 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. However, some browsers and client devices impose a 2083-character limit on the length of the URL.
Information that is passed in a query string can be tampered with by a malicious user. Do not rely on query strings to convey important or sensitive data. Additionally, a user can bookmark the URL or send the URL to other users, thereby
passing that information along with it..
In order for query string values to be available during page processing, you must submit the page using an HTTP GET command. That is, you cannot take advantage of a query string if a page is processed in response to an HTTP POST command.
We pass the value from one page to another page by query string, we write the syntax as
1) Response.Redirect("Default.aspx?query=John Smith");
where "query" is query string variable and "John Smith" is the string value for query variable.
Now we access the value on Default.aspx page as
2) we pass the multiple parameter by query string then we write the syntax as
Response.Redirect("Default.aspx?query1=John Smith &query2=krish");
Now we access the value on Default.aspx page as
string query1=Request.QueryString["query1"].toString(); string query2=Request.QueryString["query2"].toString();
string query1=Request.QueryString.toString(); string query2=Request.QueryString.toString();
string query1=Request.Params.toString(); string query2=Request.Params.toString();
3) We pass the any value by query string as
string str="JohnSmith"; Response.Redirect("Default.aspx?query="+str);
And access these value on another page by
Advantages of using query strings are:
· No server resources are required- The query string is contained in the HTTP request for a specific URL.
· Widespread support- Almost all browsers and client devices support using query strings to pass values.
· Simple implementation- ASP.NET provides full support for the query-string method, including methods of reading query strings using the Params property of the HttpRequest object.
Disadvantages of using query strings are:
· Potential security risks- The information in the query string is directly visible to the user via the browser's user interface. A user can bookmark the URL or send the URL to other users, thereby passing the information in the query string along with it. If you are concerned about any sensitive data in the query string, consider using hidden fields in a form that uses POST instead of using query strings.
· Limited capacity- Some browsers and client devices impose a 2083-character limit on the length of URLs.
Client-Side State Management Summary
The following table lists the client-side state management options that are available with ASP.NET, and provides recommendations about when you should use each option.
State management option
Use when you need to store small amounts of information for a page that will post back to itself. Using the ViewState property provides functionality with basic security.
Use when you need to store small amounts of state information for a control between round trips to the server.
Use when you need to store small amounts of information for a page that will post back to itself or to another page, and when security is not an issue.
You can use a hidden field only on pages that are submitted to the server.
Use when you need to store small amounts of information on the client and security is not an issue.
Use when you are transferring small amounts of information from one page to another and security is not an issue.
You can use query strings only if you are requesting the same page, or another page via a link.
Server Side State Management
ASP.NET offers you a variety of ways to maintain state information on the server, rather than persisting information on the client. With server-based state management, you can decrease the amount of information sent to the client in order to preserve state, however it can use costly resources on the server. The following sections describe three server-based state management features: application state, session state, and profile properties.
ASP.NET allows you to save values using application state — which is an instance of the HttpApplicationState class — for each active Web application. Application state is a global storage mechanism that is accessible from all pages in the Web application. Thus, application state is useful for storing information that needs to be maintained between server round trips and between requests for pages. Application state is stored in a key/value dictionary that is 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.
Advantages of using application state are:
- Simple implementation- Application state is easy to use, familiar to ASP developers, and consistent with other .NET Framework classes.
- Application scope- Because application state is accessible to all pages in an application, storing information in application state can mean keeping only a single copy of the information (for instance, as opposed to keeping copies of information in session state or in individual pages).
Disadvantages of using application state are:
· Application scope- The scope of application state can also be a disadvantage. Variables stored in application state are global only to the particular process the application is running in, and each application process can have different values. Therefore, you cannot rely on application state to store unique values or update global counters in Web-garden and Web-farm server configurations.
· Limited durability of data- Because global data that is stored in application state is volatile, it will be lost if the Web server process containing it is destroyed, such as from a server crash, upgrade, or shutdown.
· Resource requirements- Application state requires server memory, which can affect the performance of the server as well as the scalability of the application.
//Set values in Application State
Application["Message"] = "Welcome to MindStick Website";
Application["Message"] = "Welcome to MindStick Website";
//Get values from Application State
string message = Application["Message"] asstring;
ASP.NET allows you to save values by 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 user session will have a different session state. In addition, if a user leaves your application and then returns later, the second user session will have a different session state from the first.
Session state is structured as a key/value dictionary for storing session-specific information that needs to be maintained between server round trips and between requests for pages.
You can use session state to accomplish the following tasks:
§ Uniquely identify browser or client-device 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. Depending on which options you specify, session information can be stored in cookies, on an out-of-process server, or on a computer running Microsoft SQL Server.
Advantages of using session state are:
· Simple implementation- The session-state facility is easy to use, familiar to ASP developers, and consistent with other .NET Framework classes.
· Session-specific events- Session management events can be raised and used by your application.
· Data persistence- Data placed in session-state variables can be preserved through Internet Information Services (IIS) restarts and worker-process restarts without losing session data because the data is stored in another process space. Additionally, session-state data can be persisted across multiple processes, such as in a Web farm or a Web garden.
· Platform scalability- Session state can be used in both multi-computer and multi-process configurations, therefore optimizing scalability scenarios.
· Cookieless support- Session state works with browsers that do not support HTTP cookies, although session state is most commonly used with cookies to provide user identification facilities to a Web application. Using session state without cookies, however, requires that the session identifier be placed in the query string, which is subject to the security issues stated in the query string section of this topic.
· Extensibility- You can customize and extend session state by writing your own session-state provider. Session state data can then be stored in a custom data format in a variety of data storage mechanisms, such as a database, an XML file, or even to a Web service
Disadvantage of using session state are:
· Performance considerations- Session-state variables stay in memory until they are either removed or replaced, and therefore can degrade server performance. Session-state variables that contain blocks of information, such as large datasets, can adversely affect Web-server performance as server load increases.
// Set value in Seesion
//Get value from Session
string strId = Convert.ToString(Session["AdminSession"];
//Remove session values
ASP.NET provides a feature called profile properties, which allows you to store user-specific data. This feature is similar to session state, except that the profile data is not lost when a user's session expires. The profile-properties feature uses an ASP.NET profile, which is stored in a persistent format and associated with an individual user. The ASP.NET profile allows you to easily manage user information without requiring you to create and maintain your own database. In addition, the profile makes the user information available using a strongly typed API that you can access from anywhere in your application. You can store objects of any type in the profile. The ASP.NET profile feature provides a generic storage system that allows you to define and maintain almost any kind of data while still making the data available in a type-safe manner.
To use profile properties, you must configure a profile provider. ASP.NET includes a SqlProfileProvider class that allows you to store profile data in a SQL database, but you can also create your own profile provider class that stores profile data in a custom format and to a custom storage mechanism such as an XML file, or even to a web service.
Because data that is placed in profile properties is not stored in application memory, it is preserved through Internet Information Services (IIS) restarts and worker-process restarts without losing data. Additionally, profile properties can be persisted across multiple processes such as in a Web form or a Web garden.
Advantages of using profile properties are:
· Data persistence- Data placed in profile properties is preserved through IIS restarts and worker-process restarts without losing data because the data is stored in an external mechanism. Additionally, profile properties can be persisted across multiple processes, such as in a Web farm or a Web garden.
· Platform scalability- Profile properties can be used in both multi-computer and multi-process configurations, therefore optimizing scalability scenarios.
· Extensibility - In order to use profile properties, you must configure a profile provider. ASP.NET includes a SqlProfileProvider class that allows you to store profile data in a SQL database, but you can also create your own profile provider class that stores profile data in a custom format and to a custom storage mechanism, such as an XML file, or even to a Web service. Disadvantages of using profile properties are:
· Performance considerations- Profile properties are generally slower than using session state because instead of storing data in memory, the data is persisted to a data store.
· Additional configuration requirements- Unlike session state, the profile properties feature requires a considerable amount of configuration to use. To use profile properties, you must not only configure a profile provider, but you must pre-configure all of the profile properties that you want to store.
· Data maintenance- Profile properties require a certain amount of maintenance. Because profile data is persisted to non-volatile storage, you must make sure that your application calls the appropriate cleanup mechanisms, which are provided by the profile provider, when data becomes stale.
System.Web, Version=22.214.171.124, Culture=neutral, PublicKeyToken=b03f5f7f11d50a3a"/>
The following code is used to save the users
.Save() method updates the
profile data source with changed
profile property values.
Profile.Name = txtfullname.Text;
Profile.DateofBirth = Convert.ToDateTime(txtdateofbirth.Text);
Profile.AboutMe = txtaboutme.Text;
Profile.Designation = txtdesignation.Text;
Profile.Employer = txtemployer.Text;
Profile.Languages = txtlanguages.Text;
Profile.Place = txtplace.Text;
Profile.Project = txtproject.Text;
Profile.University = txtusername.Text;
In some cases, you might want to use database support to maintain state on your Web site. Typically, database support is used in conjunction with cookies or session state. For example, it is common for an e-commerce Web site to maintain state information by using a relational database for the following reasons:
· Data mining
The following are typical features of a cookie-supported database Web site:
· Security The visitor types an account name and password into a site logon page. The site infrastructure queries the database with the logon values to determine whether the user has rights to utilize your site. If the database validates the user information, the Web site will distribute a valid cookie containing a unique ID for that user on that client computer. The site grants access to the user.
· Personalization With security information in place, your site can distinguish each user by reading the cookie on the client computer. Typically, sites have information in the database that describes the preferences of a user (identified by a unique ID). This relationship is known as personalization. The site can research the user's preferences using the unique ID contained in the cookie, and then place content and information in front of the user that pertains to the user's specific wishes, reacting to the user's preferences over time.
· Consistency If you have created a commerce Web site, you might want to keep transactional records of purchases made for goods and services on your site. This information can be reliably saved in your database and referenced by the user's unique ID. It can be used to determine whether a purchase transaction has been completed, and to determine the course of action if a purchase transaction fails. The information can also be used to inform the user of the status of an order placed using your site.
· Data mining Information about your site usage, your visitors, or your product transactions can be reliably stored in a database. For example, your business development department might want to use the data collected from your site to determine next year's product line or distribution policy. Your marketing department might want to examine demographic information about users on your site. Your engineering and support departments might want to look at transactions and note areas where your purchasing process could be improved. Most enterprise-level relational databases, such as Microsoft SQL Server, contain an expansive toolset for most data mining projects.
By designing the Web site to repeatedly query the database by using the unique ID during each general stage in the above scenario, the site maintains state. In this way, the user perceives that the site is remembering and reacting to him or her personally.
Advantages of using a database to maintain state are:
· Security- Access to databases requires rigorous authentication and authorization.
· Storage capacity- you can store as much information as you like in a database.
· Data persistence- Database information can be stored as long as you like, and it is not subject to the availability of the Web server.
· Robustness and data integrity- Databases include various facilities for maintaining good data, including triggers and referential integrity, transactions, and so on. By keeping information about transactions in a database (rather than in session state, for example), you can recover from errors more readily.
· Accessibility- The data stored in your database is accessible to a wide variety of information-processing tools.
· Widespread support- there is a large range of database tools available, and many custom configurations are available.
Disadvantages of using a database to maintain state are:
· Complexity- Using a database to support state management requires that the hardware and software configurations be more complex.
· Performance considerations- Poor construction of the relational data model can lead to scalability issues. Also, leveraging too many queries to the database can adversely affect server performance.
Server-Side State Management Summary
The following table lists the server-side state management options that are available with ASP.NET, and provides recommendations about when you should use each option.
State management option
Use when you are storing infrequently changed, global information that is used by many users, and security is not an issue. Do not store large quantities of information in application state.
Use when you are storing short-lived information that is specific to an individual session and security is an issue. Do not store large quantities of information in session state. Be aware that a session-state object will be created and maintained for the lifetime of every session in your application. In applications hosting many users, this can occupy significant server resources and affect scalability.
Use when you are storing user-specific information that needs to be persisted after the user session is expired and needs to be retrieved again on subsequent visits to your application.
Use when you are storing large amounts of information, managing transactions, or the information must survive application and session restarts. Data mining is a concern, and security is an issue.