Monday, November 26, 2007

Don't store request variables in the ViewState!

I've been mucking around with (D)LINQ all week (this will probably be its own series of posts if I get around to it) and as a part of this, I've been reading a lot of blogs (no-thanks to Microsoft's lack of implementation demos).  Something I've noticed in a few entries is storing a variable available in the Requests body in the pages ViewState.

public partial class _Default : System.Web.UI.Page
{
    protected void Page_Load(object sender, EventArgs e)
    {
        if (!Page.IsPostBack)
        {
            if (!string.IsNullOrEmpty(Request["id"]))
                Id = Convert.ToInt32(Request["Id"]);
        }
    }

    protected void Button1_Click(object sender, EventArgs e)
    {
        Controls.Add(new LiteralControl(string.Format("Id is {0}", Id)));
    }

    protected int Id
    {
        get
        {
            object o = ViewState["Id"];

            return (o == null ? -1 : (int)o);
        }
        set { ViewState["Id"] = value; }
    }
}

I can think of a few reasons why this is unnecessary:

  1. During any ASP.NET client-server interaction on this page, the exact URL will be used hence the data will always be available in the HttpRequest object
  2. Adds to viewstate (obviously) = increased transit size and time-to-serve
  3. Serialization/deserialization on every hit

Since it's available on every request, don't bother yourself with the viewstate, save a few lines of code and just grab it from the Request during the pages Load event:

public partial class _Default : System.Web.UI.Page
{
    int Id;

    protected void Page_Load(object sender, EventArgs e)
    {
        if (!string.IsNullOrEmpty(Request["id"]))
            Id = Convert.ToInt32(Request["Id"]);

        if (!Page.IsPostBack)
        {
           // Do stuff...
        }
    }

    protected void Button1_Click(object sender, EventArgs e)
    {
        Controls.Add(new LiteralControl(string.Format("Id is {0}", Id)));
    }   
}

As an added bonus, the HttpRequest is available much earlier in the page lifecycle (before the viewstate) permitting initial events access to this (you would of course need to parse it much earlier too).

2 comments:

Pavithra M said...


It is really a great work and the way in which u r sharing the knowledge is excellent.
Thanks for helping me to understand basic concepts. As a beginner in Dot Net programming your post help me a lot.Thanks for your informative article.
Dot Net Training in chennai | Dot Net Training in velachery

Mithun Mithun said...

Given so much information in it. its very useful .perfect explanation about Dot net framework.Thanks for your valuable information. dot net training and placement in chennai | dot net training institute in velachery