ASP.NET ViewStateParameter

By Fons Sonnemans, 30-5-2007

I like the ASP.NET 2.0 DataSource controls. They are very flexible and easy to use. It has some great parameters like SessionParameter and ControlParameter. It doesn't have a ViewStateParameter. I have written it myself to fill this gap.

using System;
using System.Data;
using System.Configuration;
using System.Web;
using System.Web.Security;
using System.Web.UI;
using System.Web.UI.WebControls;
using System.Web.UI.WebControls.WebParts;
using System.Web.UI.HtmlControls;

namespace ClassLibrary1 {

    public class ViewStateParameter : Parameter {

        private String _key;

        public String Key {
            get {
                return _key;
            }
            set {
                _key = value;
            }
        }

        protected override object Evaluate(HttpContext context, Control control) {
            Type t = control.Page.GetType();
            System.Reflection.PropertyInfo pi = t.GetProperty("ViewState", System.Reflection.BindingFlags.Instance | System.Reflection.BindingFlags.NonPublic);
            StateBag pageViewState = pi.GetValue(control.Page, null) as StateBag;
            return pageViewState[Key];
        }
    }
}

My solution uses Reflection to retrieve the ViewState out of the Page. You will need FullTrust to use the code, bummer.

Download the source + sample website here.
Tags: Web, ASP.NET

Leave a Comment

Leave a Comment
Name
Comment
4 + 1 =

0 Comments

All postings/content on this blog are provided "AS IS" with no warranties, and confer no rights. All entries in this blog are my opinion and don't necessarily reflect the opinion of my employer or sponsors. The content on this site is licensed under a Creative Commons Attribution By license.