Access ViewState from Static method in aspx page
suppose i have one static method and i need to access viewstate开发者_StackOverflow from that method...how could i do so...i know it is not possible but there must be some way out.
[WebMethod]
public static string GetData(int CustomerID)
{
string outputToReturn = "";
ViewState["MyVal"]="Hello";
return outputToReturn;
}
You can get the reference to the page via HttpContext.CurrentHandler. But since Control.ViewState
is protected you can't access it (without using reflection) as opposed to the Session
which is accessible via HttpContext.Current.Session
.
So either don't use a static method, use the Session
or use this reflection 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 won't work if called via WebService, because then it's outside of Page-Lifecycle.
You might be able use [WebMethod(EnableSession=true)]
for your PageMethod
, and use Session
instead of ViewState
. Remember, with a static PageMethod
no instance of the Page class is ever created, so nice things like ViewState
simply are not there and there is no way to make them be there.
I tried this and worked for me:
Create a class conteining the properties of the viewState you want to access to
In the constructor pass the real ViewState
Create a static instance of the class but not initialize it
In the PageLoad initialize Not static class and the static one
Access the ViewState using static class properties
public class Repository
{
public int a
{
get
{
if (_viewState["a"] == null)
{
return null;
}
return (int)_viewState["a"];
}
set
{
_viewState["a"] = 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;
}
精彩评论