Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Access ViewState from Static method in aspx page

Tags:

asp.net

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;
 }
like image 788
Thomas Avatar asked Sep 05 '11 14:09

Thomas


1 Answers

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.

like image 96
Tim Schmelter Avatar answered Sep 30 '22 04:09

Tim Schmelter