【问题标题】:How could I access the ViewState of the current page using HttpContext?如何使用 HttpContext 访问当前页面的 ViewState?
【发布时间】:2011-06-10 16:07:19
【问题描述】:

如何使用 HttpContext 访问当前页面的 ViewState

我有一个需要实现的 ViewStateUtil 类:

    public static T GetViewState<T>(ViewStateKey viewStateKey)
    {
       // how to implement it?! HttpContext.Current...?
    }

【问题讨论】:

    标签: viewstate httpcontext


    【解决方案1】:
        private static T GetViewState<T>(string name)
        {
            return (T) ((BasePage)HttpContext.Current.CurrentHandler).PageViewState[name];
        }
    

    我添加了一个新的 PageViewState 属性,并让我的所有页面都从我的 BasePage 继承以公开 ViewState,然后能够获取或设置它。

    【讨论】:

      【解决方案2】:

      如果您只需要对当前页面的 ViewState 进行快速而肮脏的访问,那么从一个新的 Page 类继承我就很麻烦。

      反射是神奇的(如果慢...当然不要大量使用这个 aceessor!)

      var pageType = typeof( Page );
      var viewStatePropertyDescriptor = pageType.GetProperty( "ViewState", System.Reflection.BindingFlags.Instance | System.Reflection.BindingFlags.NonPublic );
      var currentPageViewState = (StateBag)viewStatePropertyDescriptor.GetValue( HttpContext.Current.CurrentHandler );
      // Now use currentPageViewState["whatYouWant"]
      

      【讨论】:

        猜你喜欢
        • 1970-01-01
        • 2015-09-23
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 2021-07-25
        相关资源
        最近更新 更多