State Management in ASP.NET Client Side
State management means to preserve the state of a control, web page, object/data, and user in the application explicitly because all ASP.NET web applications are stateless, i.e., by default, for each page posted to the server, the state of controls is lost. Nowadays all web apps demand a high level of state management from control to application level.
Client side
1.Hidden Field
2.View State
3.Cookies
4.Query Strings
5.Control State
1. Hidden field
Hidden field is a control provided by ASP.NET which is used to store small amounts of data on the client. It stores one value for the variable and it is a preferable way when a variable's value is changed frequently. Hidden field control is not rendered to the client (browser) and it is invisible on the browser. A hidden field travels with every request like a standard control’s value.
Eg.<asp:HiddenField ID="HiddenField1" runat="server"/>
In the code-behind page:
protectedvoid Page_Load(object sender, EventArgs e)
{
if (HiddenField1.Value != null)
{
int val= Convert.ToInt32(HiddenField1.Value) + 1;
HiddenField1.Value = val.ToString();
Label1.Text = val.ToString();
}
}
protectedvoid Button1_Click(object sender, EventArgs e)
{
//this is No Action Button Click
}
2. View State
View state is another client side state management mechanism provided by ASP.NET to store user's data, i.e., sometimes the user needs to preserve data temporarily after a postback, and then the view state is the preferred way for doing it. It stores data in the generated HTML using a hidden field, not on the server.
View State provides page-level state management i.e., as long as the user is on the current page, the state is available and the user redirects to the next page and the current page state is lost. View State can store any type of data because it is object type but it is preferable not to store a complex type of data due to the need for serialization and deserialization on each post back. View state is enabled by default for all server-side controls of ASP.NET with a property EnableviewState set to true.
Eg.protectedvoid Page_Load(object sender, EventArgs e)
{
if (IsPostBack)
{
if (ViewState["count"] != null)
{
int ViewstateVal = Convert.ToInt32(ViewState["count"]) + 1;
Label1.Text = ViewstateVal.ToString();
ViewState["count"]=ViewstateVal.ToString();
}
else
{
ViewState["count"] = "1";
}
}
}
protectedvoid Button1_Click(object sender, EventArgs e)
{
Label1.Text=ViewState["count"].ToString();
}
3. Cookies
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.
You can use cookies to store information about a particular client, session, or application. The cookies are saved on the client device, and when the browser requests a page, the client 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.
Types of Cookies
1. Persistence Cookie: Cookies which you can set an expiry date-time are called persistence cookies. Persistence cookies are permanently stored until the time you set.
Let us see how to create persistence cookies. There are two ways, the first one is:
Response.Cookies["nameWithPCookies"].Value = "This is A Persistance Cookie";
Response.Cookies["nameWithPCookies"].Expires = DateTime.Now.AddSeconds(10);
And the second one is:
HttpCookie aCookieValPer = new HttpCookie("Persistence");
aCookieValPer.Value = "This is A Persistence Cookie";
aCookieValPer.Expires = DateTime.Now.AddSeconds(10);
Response.Cookies.Add(aCookieValPer);
2. Non-Persistence Cookie: Non-persistence cookies are not permanently stored on the user client hard disk folder. It maintains user information as long as the user accesses the same browser. When the user closes the browser the cookie will be discarded. Non Persistence cookies are useful for public computers.
Let us see how to create non-persistence cookies. There are two ways, the first one is:
Response.Cookies["nameWithNPCookies"].Value = "This is A Non-Persistence Cookie";
And the second way is:
HttpCookie aCookieValNonPer = new HttpCookie("NonPersistance");
aCookieValNonPer.Value = "This is A Non Persistance Cookie;
Response.Cookies.Add(aCookieValNonPer);
How to read a cookie:
if (Request.Cookies["NonPersistance"] != null)
Label2.Text = Request.Cookies["NonPersistance"].Value;
4. Query String
A query string is a value specified in an HTTP query that can be accessed easily within ASP.NET. The query string is appended at the end of the URL following the question mark (‘?’) character. Multiple query strings can be specified in the URL by separating them by either an ampersand (‘&’) or a semicolon (‘;’). The following is an example of the query string with a field name of ‘id’ and a value of ‘1’: http://www.shshblogs.com/default.aspx?id=1. Query strings can be used for many different reasons, one common use is to display different data on the same page based on the query string. For example, if I had an online store and wanted a page to display an individual item from my database on the page, we could use a query string. This would work by passing something such as the item’s id in the database as a query string to the page, and then displaying data from the database based on the value of the query string.
//output the id query string
Response.Write(Request.QueryString["id"]);
Response.Write("<br/>");
//output the number of query strings
Response.Write("Number of Query String Parameters: " + Request.QueryString.Count.ToString())
Note: - This code will display two values that are of interest to us. First, the value of the query string named ‘id’ and then the total number of query string parameters that are found in our URL. To access the query string from the front end, add in the following to the Default.aspx page:
5. Control State
Control State is another client side state management technique. Whenever we develop a custom control and want to preserve some information, we can use view state but suppose view state is disabled explicitly by the user, the control will not work as expected. For expected results for the control, we have to use Control State property. Control state is separate from view state.
How to use control state property: Control state implementation is simple. First, override the OnInit() method of the control and add a call for the Page.RegisterRequiresControlState() method with the instance of the control to register. Then override LoadControlState and SaveControlState in order to save the required state information.
0 comments
Post a Comment