Access ViewState from static method on aspx page

Suppose I have one static method, and I need to access the viewstate from this method ... how can I do this ... I know this is not possible, but there must be some way out.

[WebMethod] public static string GetData(int CustomerID) { string outputToReturn = ""; ViewState["MyVal"]="Hello"; return outputToReturn; } 
+7
source share
3 answers

You can get the link to the page through HttpContext.CurrentHandler . But since Control.ViewState is protected , you cannot access it (without using reflection), unlike Session , accessible through HttpContext.Current.Session .

Thus, either do not use the static method, use Session , or use this approach:

 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); } 

However, this will not work if called through a WebService, because then it is outside the Page-Lifecycle .

+13
source

You can use [WebMethod(EnableSession=true)] for your PageMethod and use Session instead of ViewState . Remember that with a static PageMethod instance of the Page 1 class is never created, so there are simply no pleasant things like ViewState , and there is no way to make them be there.

+9
source

I tried this and worked for me:

  • Create a class that maps the viewState properties that you want to access,
  • In the constructor, pass the real ViewState
  • Create a static instance of the class, but do not initialize it
  • In PageLoad initialization is not a static class and static
  • Access ViewState Using Static Class Properties

-

 public class Repository { public int a { get { if (_viewState["a"] == null) { return null; } return (int)_viewState["a"]; } set { _viewState["ActiveGv"] = value; } } public StateBag _viewState; public Repository(StateBag viewState) { _viewState = viewState; } } static Repository staticRepo; protected void Page_Load(object sender, EventArgs e) { Repository repo = new Repository(ViewState); staticRepo = repo; } public static void testMethod() { int b = staticRepo.a; } 
+1
source

All Articles