How could I access the ViewState of the current page using HttpContext?

时光总嘲笑我的痴心妄想 提交于 2019-12-07 23:16:16

问题


How could I access the ViewState of the current page using HttpContext

I have a ViewStateUtil class that I'd need to implement:

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

回答1:


    private static T GetViewState<T>(string name)
    {
        return (T) ((BasePage)HttpContext.Current.CurrentHandler).PageViewState[name];
    }

I added a new PageViewState property and let all my pages inherit from my BasePage to expose ViewState then being able to get or set it.




回答2:


It troubles me to inherit from a new Page class if you need only one quick and dirty acces to the current page's ViewState.

Reflexion is magic (if slow... do not make heavy using of this aceessor, of course!)

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"]


来源:https://stackoverflow.com/questions/6309075/how-could-i-access-the-viewstate-of-the-current-page-using-httpcontext

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!