Wednesday, April 14, 2010

State Management (View State)

State Management (View State)

I Love the view of Lotus Pond. Look at the Raising Sober Rain.(Init,Load View State,Load Postback Data,Load,Raise Postback Event,Save View State,Render)

Web Pages developed in ASP.Net are HTTP based and HTTP protocol is a stateless protocol. It means that web server does not have any idea about the requests from where they coming i.e from same client or new clients. On each request web pages are created and destroyed.

State(Cache) management is the process by which you maintain state and page information over multiple requests for the same or different pages.

There are two ways to maintain the state(Cache) of web form.
1.Client-Side State Management
2.Server-Side State Management


1. Client-Side State Mangement :- In client side state management we store the information in the page or in client computer, no information is stored on the server between round trips.
There are four ways for Client Side State Management
A. View State
B. Cookies
C. Hidden Field
D. Query String

A. View State :- When a form is submitted in classic ASP, all form values are cleared. Suppose you have submitted a form with a lot of information and the server comes back with an error. You will have to go back to the form and correct the information. You click the back button, and what happens.......ALL form values are CLEARED, and you will have to start all over again! The site did not maintain your ViewState.
When a form is submitted in ASP .NET, the form reappears in the browser window together with all form values. How come? This is because ASP .NET maintains your ViewState.
Each control on a Web Forms page, including the page itself, has a EnableViewState property, it is a built-in structure for automatic retention of page and control state. By default it is true for every control.
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 ViewState 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.
The hidden field name is __ViewState and id is __ViewState.
The ViewState property is defined in the System.Web.UI.Control class, meaning that all ASP.NET server controls have this property available.
What manages the view state is the StateBag class. This class is like a dictionary—you may store key/value pairs in it.
View State can be use as dictionary object and user can save custom values there on code behind.

ViewState["ViewStateVariable"]=1;
By default value of EnableViewState is true for each control.

Session State View State
Holds server resources? Yes No
Times out? Yes – after 20 minutes (default) No
Stores any .NET type? Yes No, limited support for: strings, integers, Booleans, arrays, ArrayList, hashtable, PairS, TripletS, custom TypeConverters
Increases "HTML payload"? No Yes

Storing Objects in View State

--> You can store your own objects in view state just as easily as you store numeric and string types. However, to store an item in view state, ASP.NET must be able to convert it into a stream of bytes so that it can be added to the hidden input field in the page. This process is called serialization. If your objects aren't serializable (and by default they aren't), you'll receive an error message when you attempt to place them in view state.
To make your objects serializable, all you need to do is to add the 'Serializable' attribute before your class declaration. For example, here's an exceedingly simple Student class:
[Serializable]
public class Student
{
public string firstName;
public string lastName;

public Student(string fName, string lName)
{
firstName = fName;
lastName = lName;
}
}
Because the Student class is marked as serializable, it can be stored in view state:
// Storing a student in view state.
Student stud = new Student("John", "Doe");
ViewState["CurrentStudent"] = stud;
Remember, when using custom objects, you'll need to cast your data when you retrieve it from view state.
// Retrieve a student from view state.
Student stud = (Student) ViewState["CurrentCustomer"];
To be serializable, your classes you must meet these requirements:
• Your class must have the Serializable attribute.
• Any classes it derives from must have the Serializable attribute.
• All the private variables of the class must be serializable data types. Any nonserializable data type must be decorated with the NonSerialized attribute (which means it is simply ignored during the serialization process.

Can I Get Rid Of View State Completely?

No. You will always have a relatively short string representing the page itself even if you turn off the view state on each and every control.
When ViewState Load and Save
Before we can dive into our examination of Loading stage of ViewState it is important that we take a quick moment to discuss the ASP .Net page life cycle in short.


Stage 1 - Initialization

After the control hierarchy has been built, the Page, along with all of the controls in its control hierarchy, enter the initialization stage. This stage is marked by having the Page and controls fire their Init events. At this point in the page life cycle, the control hierarchy has been constructed, and the Web control properties that are specified in the declarative syntax have been assigned.
With regards to view state it is important for two reasons; first, server controls don't begin tracking view state changes until right at the end of the initialization stage. Second, when adding dynamic controls that need to utilize view state, these controls will need to be added during the Page's Init event as opposed to the Load event, as we'll see shortly.

Stage 2 - Load View State

The load view state stage only happens when the page has been posted back. During this stage, the view state data that had been saved from the previous page visit is loaded and recursively populated into the control hierarchyof the Page. It is during this stage that the view state is validated.

Stage 3 - Load Postback Data

The load postback data stage also only happens when the page has been posted back. A server control can indicate that it is interested in examining the posted back data by implementing the IPostBackDataHandler interface. In this stage in the page life cycle, the Page class enumerates the posted back form fields, and searches for the corresponding server control. If it finds the control, it checks to see if the control implements the IPostBackDataHandler interface. If it does, it hands off the appropriate postback data to the server control by calling the control's LoadPostData() method. The server control would then update its state based on this postback data.
To help clarify things, let's look at a simple example. One nice thing about ASP.NET is that the Web controls in a Web Form remember their values across postback. That is, if you have a TextBox Web control on a page and the user enters some value into the TextBox and posts back the page, the TextBox's Text property is automatically updated to the user's entered value. This happens because the TextBox Web control implements the IPostBackDataHandler interface, and the Page class hands off the appropriate value to the TextBox class, which then updates its Text property.
To concretize things, imagine that we have an ASP.NET Web page with a TextBox whose ID property is set to txtName. When the page is first visited, the following HTML will be rendered for the TextBox: . When the user enters a value into this TextBox (such as, "Hello, World!") and submits the form, the browser will make a request to the same ASP.NET Web page, passing the form field values back in the HTTP POST headers. These include the hidden form field values (such as __VIEWSTATE), along with the value from the txtName TextBox.
When the ASP.NET Web page is posted back in the load postback data stage, the Page class sees that one of the posted back form fields corresponds to the IPostBackDataHandler interface. There is such a control in the hierarchy, so the TextBox's LoadPostData() method is invoked, passing in the value the user entered into the TextBox ("Hello, World!"). The TextBox's LoadPostData() method simply assigns this passed in value to its Text property.
Notice that in our discussion on the load postback data stage, there was no mention of view state. You might naturally be wondering, therefore, why I bothered to mention the load postback data stage in an article about view state. The reason is to note the absence of view state in this stage. It is a common misconception among developers that view state is somehow responsible for having TextBoxes, CheckBoxes, DropDownLists, and other Web controls remember their values across postback. This is not the case, as the values are identified via posted back form field values, and assigned in the LoadPostData() method for those controls that implement IPostBackDataHandler.

Stage 4 - Load

This is the stage with which all ASP.NET developers are familiar, as we've all created an event handler for a page's Load event (Page_Load). When the Load event fires, the view state has been loaded (from stage 2, Load View State), along with the postback data (from stage 3, Load Postback Data). If the page has been posted back, when the Load event fires we know that the page has been restored to its state from the previous page visit.

Stage 5 - Raise Postback Event

Certain server controls raise events with respect to changes that occurred between postbacks. For example, the DropDownList Web control has a SelectedIndexChanged event, which fires if the DropDownList's SelectedIndex has changed from the SelectedIndex value in the previous page load. Another example: if the Web Form was posted back due to a Button Web control being clicked, the Button's Click event is fired during this stage.
There are two flavors of postback events. The first is a changed event. This event fires when some piece of data is changed between postbacks. An example is the DropDownLists SelectedIndexChanged event, or the TextBox's TextChanged event. Server controls that provide changed events must implement the IPostBackDataHandler interface. The other flavor of postback events is the raised event. These are events that are raised by the server control for whatever reason the control sees fit. For example, the Button Web control raises the Click event when it is clicked, and the Calendar control raises the VisibleMonthChanged event when the user moves to another month. Controls that fire raised events must implement the IPostBackEventHandler interface.
Since this stage inspects postback data to determine if any events need to be raised, the stage only occurs when the page has been posted back. As with the load postback data stage, the raise postback event stage does not use view state information at all. Whether or not an event is raised depends on the data posted back in the form fields.

Stage 6 - Save View State

In the save view state stage, the Page class constructs the page's view state, which represents the state that must persist across postbacks. The page accomplishes this by recursively calling the SaveViewState() method of the controls in its control hierarchy. This combined, saved state is then serialized into a base-64 encoded string. In stage 7, when the page's Web Form is rendered, the view state is persisted in the page as a hidden form field.

Stage 7 - Render

In the render stage the HTML that is emitted to the client requesting the page is generated. The Page class accomplishes this by recursively invoking the RenderControl() method of each of the controls in its hierarchy.

The Role of View State

View state's purpose in life is simple: it's there to persist state across postbacks. (For an ASP.NET Web page, its state is the property values of the controls that make up its control hierarchy.) This begs the question, "What sort of state needs to be persisted?" To answer that question, let's start by looking at what state doesn't need to be persisted across postbacks. Recall that in the instantiation stage of the page life cycle, the control hierarchy is created and those properties that are specified in the declarative syntax are assigned. Since these declarative properties are automatically reassigned on each postback when the control hierarchy is constructed, there's no need to store these property values in the view state.
For example, imagine we have a Label Web control in the HTML portion with the following declarative syntax:
<asp:label name="Verdana" runat="server" text="Hello, World!"></asp:label>

When the control hierarchy is built in the instantiation stage, the Label's Text property will be set to "Hello, World!" and its Font property will have its Name property set to Verdana. Since these properties will be set each and every page visit during the instantiation stage, there's no need to persist this information in the view state.
What needs to be stored in the view state is any programmatic changes to the page's state. For example, suppose that in addition to this Label Web control, the page also contained two Button Web controls, a Change Message Button and an Empty Postback button. The Change Message Button has a Click event handler that assigns the Label's Text property to "Goodbye, Everyone!"; the Empty Postback Button just causes a postback, but doesn't execute any code. The change to the Label's Text property in the Change Message Button would need to be saved in the view state. To see how and when this change would be made, let's walk through a quick example. Assuming that the HTML portion of the page contains the following markup:
And the code-behind class contains the following event handler for the Button's Click event:
private void btnSubmit_Click(object sender, EventArgs e)
{
lblMessage.Text = "Goodbye, Everyone!";
}
Figure 4 illustrates the sequence of events that transpire, highlighting why the change to the Label's Text property needs to be stored in the view state.
ms972976.viewstate_fig04(en-us,MSDN.10).gif
To understand why saving the Label's changed Text property in the view state is vital, consider what would happen if this information were not persisted in view state. That is, imagine that in step 2's save view state stage, no view state information was persisted. If this were the case, then in step 3 the Label's Text property would be assigned to "Hello, World!" in the instantiation stage, but would not be reassigned to "Goodbye, Everyone!" in the load view state stage. Therefore, from the end user's perspective, the Label's Text property would be "Goodbye, Everyone!" in step 2, but would seemingly be reset to its original value ("Hello, World!") in step 3, after clicking the Empty Postback button.

                                 The Cost of View State
Nothing comes for free, and view state is no exception. It imposes two performance hits whenever an ASP .Net page requested.

1. On all page visits, during the save view state stage the page class generate the collective view state for all the controls in control hierarchy and serialize the state to a base 64 encoding string. Similarly, on  postbacks, the load view state stage needs to deserialize the persisted view state data, and update the pertinent controls in the control hierarchy.

2. The__ViewState field adds extra size to web page that the client must download. For some view state-heavy pages this can be tens of kilobytes of data, __ ViewState form field must be sent back to the Web server  in the HTTP post header, thereby  increasing the postback request time


If ViewState size is too much than it can create the problem for SEO, Search Engine Optimization will not get your actual data so your site will never be in Google list or any other search engine list. You can solve this problem by moving view state tag to below of the page. you can do it on render event of the page.

<a href="http://anyurl.com" rel="tag" style="display:none">CodeProject</a>

References:
http://msdn.microsoft.com/en-us/library/ms972976.aspx
http://aspnetresources.com/articles/ViewState.aspx

No comments:

Followers

Link