Thomas Thomas - 1 year ago 158
ASP.NET (C#) Question

Access ViewState from Static method in aspx page

suppose i have one static method and i need to access viewstate from that could i do so...i know it is not possible but there must be some way out.

public static string GetData(int CustomerID)
string outputToReturn = "";
return outputToReturn;

Answer Source

You can get the reference to the page via HttpContext.CurrentHandler. But since Control.ViewState is protected you can't access it (without using reflection) as opposed to the Session which is accessible via HttpContext.Current.Session.

So either don't use a static method, use the Session or use this reflection approach:

public static string CustomerId
    get { return (string)GetCurrentPageViewState()["CustomerId"]; }
    set { GetCurrentPageViewState()["CustomerId"] = value; }

public static System.Web.UI.StateBag GetCurrentPageViewState()
    Page page = HttpContext.Current.Handler as Page;
    var viewStateProp = page?.GetType().GetProperty("ViewState",
        BindingFlags.FlattenHierarchy |
        BindingFlags.Instance |
    return (System.Web.UI.StateBag) viewStateProp?.GetValue(page);

However, this won't work if called via WebService, because then it's outside of Page-Lifecycle.