Friday, June 10, 2011

when and how to use viewstate,session,application,cookies,hidden from field

ViewState is a page level persistence and it happens only on same page where a viewstate persists page values. http://msdn2.microsoft.com/en-us/library/ms972976.aspx
Page level state is information maintained when an element on the web form page causes a subsequent request to the server for the same page – referred to as 'postback'. This is appropriately called ViewState as the data involved is usually, though not necessarily, shown to the user directly within the page output.
The Control.ViewState property is associated with each server control in your web form and provides a dictionary object for retaining values between such multiple requests for the same page. This is the 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. 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.
ViewState is enabled by default so if you view a web form page in your browser you will see a line similar to the following near the form definition in your rendered HTML:

<input type="hidden" name="__VIEWSTATE"
value="dDwxNDg5OTk5MzM7Oz7DblWpxMjE3ATl4Jx621QnCmJ2VQ==" /> 

When a page is re-loaded two methods pertaining to ViewState are called: LoadViewState and SaveViewState. Page level state is maintained automatically by ASP.NET but you can disable it, as necessary, by setting the EnableViewState property to false for either the controls whose state doesn't need to be maintained or for the page as a whole. For the control:

<asp:TextBox id=”tbName” runat=”server” EnableViewState=”false” /> 

for the page:

<%@ Page EnableViewState=”false” %> 

You can validate that these work as claimed by analyzing the information presented if you turn on tracing for a page containing the above elements. You will see that on postback, and assuming ViewState is enabled, that the LoadViewState method is executed after the Init method of the Page class has been completed. SaveViewState is called after PreRender and prior to actual page rendering.
You can also explicitly save information in the ViewState using the State Bag dictionary collection, accessed as follows:

ViewState(key) = value 

Which can then be accessed as follows:

Value = ViewState(key) 

It is important to remember that page level state is only maintained between consecutive accesses to the same page. When you visit another page the information will not be accessible via the methods above.
Session
Sessions are used to persist information which you want to pass from page to page but in a unique user scope. What that means is that each user has a unique Session and hence may have unique values.
Usage of session Session["Key"] = value (where you can assign any key and value and retrieve those values based on the key) as string myval = (string)(Session["Key"])
Application
Application allows you to persist values that are global throughout the application. So for e.g. authentication may be a global function throughout application. An example is as follows in global.asax
Sub Application_Start()
    Dim ds As New DataSet()
    Dim fs As New FileStream(Server.MapPath("schemadata.xml"),FileMode.Open,FileAccess.Read)
    Dim reader As New StreamReader(fs)
    ds.ReadXml(reader)
    fs.Close()
    Dim view As New DataView (ds.Tables(0))
    Application("Source") = view
End Sub

function Application_Start() : void {
    var ds:DataSet = new DataSet();
    var fs:FileStream = new FileStream(Server.MapPath("schemadata.xml"),FileMode.Open,FileAccess.Read);
    var reader:StreamReader = new StreamReader(fs);
    ds.ReadXml(reader);
    fs.Close();
    var view:DataView = new DataView(ds.Tables[0]);
    Application("Source") = view;
}
CookiesClient side cookies are used to store volatile user preferences as followsProtected Sub Page_Load(sender As Object, e As EventArgs)
    If Request.Cookies("preferences1") = Null Then
        Dim cookie As New HttpCookie("preferences1")
        cookie.Values.Add("ForeColor", "black")
        ...
        Response.AppendCookie(cookie)
    End If
End Sub
protected function Page_Load(sender:Object, e:EventArgs) : void {
    if (Request.Cookies("preferences1") == null) {
        var cookie:HttpCookie = new HttpCookie("preferences1");
        cookie.Values.Add("ForeColor", "black");
        ...
        Response.AppendCookie(cookie);
    }
}
  Hidden field You also can store small amounts of information on the client by using hidden fields. Hidden fields are HTML elements, similar to text boxes, where you can store strings. Web browsers don'tdisplay hidden fields in page output. However, when you use a hidden field within an HTML form, the contents are submitted back to your program and can be used in your code behind. <input type="hidden" value="Value That You Need to Store" id="KeyName">  //Setting hidden field String strValue = Request.Params["KeyName"];      // retrieving the filed.
Read more here   http://msdn2.microsoft.com/en-us/library/z1hkazw7.aspx

No comments:

Post a Comment