Tuesday, January 6, 2009

ASP.NET Viewstate

Why Viewstate?

As we know, HTTP is a state less protocol. State less means the protocol couldn't maintain state between request and response we must have to use some mechanism to accomplish this. (Like query string, cookie, etc.). When a request is sent from "Client Machine" to "Server Machine" based on the request header details, Server handover processing of request to appropriate process on the server. If the same "Client Machine" send subsequent request for the same Page, Server couldn't recognize that request is from the same machine. He just processes the request, and sends the response regardless of "Client Machine".

Consider we need to post some text fields on a page using classic ASP. Suppose some validations fails, so the response generated from server will contain on the Page HTML without the data in the text fields, as it doesn't know the present status of the page at client end. Think about the user who has filled almost 50 fields on the page, and page returns with all blank field and a validation message on top saying no data saved!!!

This was the main reason why Viewstate is introduced - to maintain the state of the page between round-trip.

What is Viewstate?

Viewstate is the ASP.NET state management technique introduced to maintain current page state between round-trip. It maintains state of the fields, using a hidden field with name = "__VIEWSTATE". It uses base64 encoding to store the state. Whenever the page is posted to the server, view state is also posted back in addition to the posted data. Click here to check more details on how hidden field is posted back to server

Here is the sample of Viewstate stored at the client side.

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

Important: As Viewstate is posted to the server each time, It should be used very carefully. Bulky Viewstate can result in performance issues. If you don't want to maintain the Viewstate, include the directive <%@ Page EnableViewState="false"%> at the top of an .aspx page If you do not want to maintain Viewstate for any control add the attribute EnableViewState="false" to any control.

No comments:

Post a Comment