问题
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