Thomas Thomas - 3 months ago 52
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 method...how could i do so...i know it is not possible but there must be some way out.

[WebMethod]
public static string GetData(int CustomerID)
{
string outputToReturn = "";
ViewState["MyVal"]="Hello";
return outputToReturn;
}

Answer

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 |
        BindingFlags.NonPublic);
    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.

Comments