Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

ViewState as Attribute

Tags:

asp.net

Instead of this ..

    public string Text
    {

        get { return ViewState["Text"] as string; }

        set { ViewState["Text"] = value; }

    }

I would like this ..

    [ViewState]
    public String Text { get; set; }

Can it be done?

like image 892
BBorg Avatar asked Nov 04 '09 14:11

BBorg


1 Answers

Like this:

public class BasePage: Page {

    protected override Object SaveViewState() {

        object baseState                      = base.SaveViewState();            
        IDictionary<string, object> pageState = new Dictionary<string, object>();
        pageState.Add("base", baseState);

        // Use reflection to iterate attributed properties, add 
        // each to pageState with the property name as the key

        return pageState;
    }

    protected override void LoadViewState(Object savedState) {

        if (savedState != null) {

            var pageState = (IDictionary<string, object>)savedState;

            if (pageState.Contains("base")) {
                base.LoadViewState(pageState["base"]);
            }

            // Iterate attributed properties. If pageState contains an
            // item with the appropriate key, set the property value.

        }
    }
}

Pages that inherit from this class could use the attribute-driven syntax you've proposed.

like image 68
Jeff Sternal Avatar answered Oct 02 '22 00:10

Jeff Sternal