Wednesday, 19 November 2014

View State In Asp.Net

  1. View state is the method that the ASP.NET page framework uses to preserve page and control values between round trips. When the HTML markup for the page is rendered, the current state of the page and values that must be retained during post back are serialized into base64-encoded strings.
  2. When an ASP.NET page is submitted to the server, the state of the controls is encoded and sent to the server at every form submission in a hidden field known as
    __VIEWSTATE. The server sends back the variable so that when the page is re-rendered, the controls render at their last state, so no extra programming is needed. If you try to view source code from browser you can see that ASP .NET has added a hidden field in the form to maintain the ViewState.
  3. Example.
  4. <html>
    <body>
    <form action="demo_classicasp.aspx" method="post">
    Your name: <input type="text" name="fname" size="20">
    <input type="submit" value="Submit">
    </form>
    <%
    dim fname
    fname=Request.Form("fname")
    If fname<>"" Then
    Response.Write("Hello " & fname & "!")
    End If
    %>
    </body>
    </html>
  5. Maintaining the ViewState is the default setting for ASP.NET Web Forms. By default, most ASP.NET controls enable view state. If you want to not maintain the ViewState, include the directive <%@ Page EnableViewState="false" %> at the top of an .aspx page or add the attribute EnableViewState="false" to any control. You can also maintain ViewState for all pages in a web.config file.

<configuration>
<system.web>
<pages
buffer="true"
enableSessionState="true"
enableViewState="true"
autoEventWireup="true"
/>
</system.web>
</configuration>

View state is a great idea to store information in a page, but if you wish to save more complex data, and keep them from page to page, you should look into using cookies or sessions is better.


0 comments::

Post a Comment

Copyright © DotNet-Ashok