I have a property in my ASP.NET application which would pull the value from database and stores it in view state. When it's called the first time, it pulls the value from the database, and then on consecutive hits, it should pull it from view state.
Now when I call the property, it always pulls the data from the database instead of getting it from the view state on consecutive hits.
Here's what I am doing:
private bool HasAccess
{
get
{
if (ViewState["HasAccess"] == null)
{
ViewState["HasAccess"] = pageDao.HasMacroAccess("HAS_ACCESS");
Response.Write("FROM DATABASE");
}
else
{
Response.Write("FROM VIEWSTATE");
}
return (bool)ViewState["HasAccess"];
}
}
Now on page load or wherever I need this property value, I simply call it. However on all hits it prints From Database message, although it should be on first hit only.
Now if I update the above code and instead of using ViewState, I use Session, then it works as expected no issues. But I want to avoid using Session and rather go for ViewState.
Is this the normal behaviour of ViewState or I am doing something wrong?
ViewState is that it can only save the values for page level access.
If you save something on FirstPage using Viewstate, it works only on FirstPage.aspx (and not on the other pages)
Try Data Caching. Caching enables you to store the expensive data into Cache object.
Cache is stored in memory rather than in page source.