Dynamic ViewState in ASP.Net WebForms – Part 2

In previous post I showed an approach combining DynamicObject with ViewState for accessing ViewState members using dynamic properties instead of string indexes. However that approach had some disadvantages:

  • It is tied some a concrete base page class.
  • It does not have all the properties/methods of StateBag class
  • Mixing ViewState and ViewBag can be confusing for new developers.

In order to overcome these issues I made several changes to the DynamicViewState class.

First of all I changed the constructor to accept a StateBag instance instead of Page class so that the DynamicViewState class does not need to be nested inside base page class. Secondly I added all the interfaces which are implemented by StateBag. This makes it fully compatible with StateBag class so we can simply rename the new property in base page class from ViewBag to ViewState. This way you can leave the old code that uses ViewState and use the new approach for all new code. Here is a sample snippet:

public partial class SamplePage : BasePage
{
    protected void Page_Load(object sender, EventArgs e)
    {
        if (IsPostBack)
        {
            ViewState.loadCount++;

            loadLabel.Text = string.Format("Load count: {0}", ViewState.loadCount);
        }
        else
        {
            ViewState["loadCount"] = 0;
            loadLabel.Text = "Load count: 0";
        }
    }
}

Getting started with DynamicViewState

If you would like to use DynamicViewState in your code the simplest way for getting it is using Nuget package available at Dynamic ViewState Nuget package. Once you add the package to your project simply change the base class of your pages to BasePage and that is all you need. Source code is available at github.

Performance Benchmarks

In a comment to previous post Jalpesh Vadgama asked about performance impact. I ran benchmark to compare dynamic implementation with ordinary ViewState usage. As expected dynamic implementation is slower but the difference is quite small:

  • Average milliseconds with dynamic: 0.0003
  • Average milliseconds without dynamic: 0.00016

As you can see dynamic access is twice slower compared to ordinary ViewState usage.

Avatar
Giorgi Dalakishvili
World-Class Software Engineer

Related