从aspx页面中的Static方法访问ViewState

Tho*_*mas 7 asp.net

假设我有一个静态方法,我需要从该方法访问viewstate ...我怎么能这样做...我知道这是不可能的,但必须有一些出路.

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

Tim*_*ter 14

您可以通过HttpContext.CurrentHandler获取对页面的引用.但是,由于Control.ViewState受到保护,您无法访问它(不使用反射),而Session不能通过它访问HttpContext.Current.Session.

所以要么不使用静态方法,要么使用Session或使用这种反射方法:

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);
}
Run Code Online (Sandbox Code Playgroud)

但是,如果通过WebService调用,这将无效,因为它在页面生命周期之外.

  • ViewState是受保护的字段,因此不起作用 (4认同)

Pet*_*erg 10

你也许可以用[WebMethod(EnableSession=true)]你的PageMethod,并使用Session替代ViewState.请记住,使用静态PageMethod不会创建Page类的实例,所以很好的东西就像那样ViewState简单,并且没有办法让它们在那里.