内容简介:翻译自:https://stackoverflow.com/questions/7309148/access-viewstate-from-static-method-in-aspx-page
假设我有一个静态方法,我需要从该方法访问viewstate …我怎么能这样做…我知道这是不可能的,但必须有一些出路.
[WebMethod]
public static string GetData(int CustomerID)
{
string outputToReturn = "";
ViewState["MyVal"]="Hello";
return outputToReturn;
}
您可以通过 HttpContext.CurrentHandler
获得对页面的引用.但是由于
Control.ViewState
受到保护,您无法访问它(不使用反射),而不是可通过HttpContext.Current.Session访问的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);
}
但是,如果通过WebService调用,则无效,因为它超出了 Page-Lifecycle .
翻译自:https://stackoverflow.com/questions/7309148/access-viewstate-from-static-method-in-aspx-page
以上所述就是小编给大家介绍的《asp.net – 从aspx页面中的Static方法访问ViewState》,希望对大家有所帮助,如果大家有任何疑问请给我留言,小编会及时回复大家的。在此也非常感谢大家对 码农网 的支持!
本站部分资源来源于网络,本站转载出于传递更多信息之目的,版权归原作者或者来源机构所有,如转载稿涉及版权问题,请联系我们。
Linux从入门到精通
刘忆智、等 / 清华大学出版社 / 2010-1-1 / 59.00元
linux是目前增长最迅速的操作系统。本书由浅入深、循序渐进地向读者介绍linux的基本使用和系统管理。全书内容包括linux概述、linux安装、linux基本配置、桌面环境基本操作、shell基本命令、文件和目录管理、软件包管理、磁盘管理、用户与用户组管理、进程管理、网络配置、浏览网页、收发邮件、文件传输和共享、远程登录、多媒体应用、图像浏览和处理、打印机配置、办公软件的使用、linux编程工......一起来看看 《Linux从入门到精通》 这本书的介绍吧!