A quick look on ASP.NET viewstate

1 04 2012

Viewstate is a cool mechanism in ASP.NET platform to maintain information supplied from the client-side. Every input will be submitted to the server with POST method by default. Some HTML input objects will contain javascript function calling back to the server as it is shown below.

function __doPostBack(eventTarget, eventArgument) {
if (!theForm.onsubmit || (theForm.onsubmit() != false)) {
theForm.__EVENTTARGET.value = eventTarget;
theForm.__EVENTARGUMENT.value = eventArgument;

This mechanism could prevent CSRF(Cross-Site Request Forgery) attack implicitly. You have to write quite a few lines of code in PHP, if you want to prevent this kind of attack. However, viewstate is a trade-off between performance and security. Thus, disable viewstate on the page or on the objects you don’t need. Enable it only whenever you need it. Use viewstate wisely.

Disable Viewstate
1. website level
In web.config, change enableViewState to false under system.web tag.

<pages enableViewState="false"></pages>

Whatever you change the properties of the control you use, the server could not maintain viewstate value.

  • Result –> Not maintain
  • Even the control was set as:
  • EnableViewState = True
    ViewStateMode = Inherit,Enable

    2.page level
    Modify the target page with,

    <%@ Page Language="C#" AutoEventWireup="true" CodeFile="YOURCODE.aspx.cs" Inherits="XXXX_Stage" EnableViewState="false" %>

    Whatever you set the control, viewstate won’t work.

  • Result –> Not maintain
  • Even the control was set as:
  • EnableViewState = True
    ViewStateMode = Inherit,Enable

    3.control level
    Bear in mind that the setting inherit viewstate’s configuration from above levels by default. Website–>Page–>Control

  • Result –> maintain
  • EnableViewState = True
    ViewStateMode = Enable

  • Result –> not maintain
  • EnableViewState = True,False
    ViewStateMode = Disable

    Tested on:
    Microsoft .NET Framework Version:4.0.30319; ASP.NET Version:4.0.30319.1



    Leave a Reply

    Fill in your details below or click an icon to log in:

    WordPress.com Logo

    You are commenting using your WordPress.com account. Log Out /  Change )

    Google+ photo

    You are commenting using your Google+ account. Log Out /  Change )

    Twitter picture

    You are commenting using your Twitter account. Log Out /  Change )

    Facebook photo

    You are commenting using your Facebook account. Log Out /  Change )


    Connecting to %s

    %d bloggers like this: