28

I stored a object in viewstate on Page. Now when i access the same viewsate object on usercontrol,it shows as null. I even tried creating the same viewstate with same name in usercontrol and page.Both holds different value.

I understand that viewstate is a protected property. How does this thing implement in above scenerio or is there any other reason for this behaviour.

Edit:

Usercontrol is there in the page markup. I am not loading it dynamically.

I have a page EditFacilityworkType.aspx. On page I have a usercontrol FacilityWorkTypeDetails.aspx(FacilityWorkTypeDetails1). Inside this usercontrol i have a user control Workflow.aspx(Workflow1)

Page_Load() of Page I am retrieving workflowdetails on page_load() of page.

 FacilityWorktype facilityWorkType = facilityDetails.GetFacilityWorktypeDetail(SessionHelper.FacilityWorkTypeID);
 ViewState["WorkFlow"] = facilityWorkType.FacilityWorkTypeWorkFlow

Inside usercontrol FacilityWorkTypeDetails.aspx. I have a property

 public FacilityWorktype FacilityWorkTypeDetails
{
    get
    {
        #region Fill FacilityWorktype
        return GetEntityFromControl();
        #endregion
    }
    set
    {
        PopulateControls(value);
    }
}

Now i set this property in page load of page

FacilityWorkTypeDetails1.FacilityWorkTypeDetails = facilityWorkType;

Inside Workflow.aspx, I have a property

/// <summary>
/// Property to fill entity object from controls on this page
/// </summary>
public WorkFlow WorkFlowDetails
{
    get
    {
        return GetEntityFromControls();
    }
    set
    {            
        BindTranscriptionMethodDDL(ddlTranscMethod);
        PopulateControls(value);
    }
}

Now PopulateControls() of FacilityWorkTypeDetails1, i am setting property of workflow1

private void PopulateControls(FacilityWorktype value) {

    Workflow1.WorkFlowDetails = value.FacilityWorkTypeWorkFlow;
}

Now when i am retrieving values from

 private WorkFlow GetEntityFromControls()
 {
     WorkFlow workFlow = (ViewState["WorkFlow"] as WorkFlow) ?? new WorkFlow();  
     //workFlow  is null

 }

So now inside this function workFlow is null. I want to ask,why is it null when i have set viewstate in page.

Rohit Raghuvansi
  • 2,824
  • 8
  • 46
  • 74
  • 2
    How (or where; code behind?) do you "store an object in viewstate on page"? If you need to store "something" "somewhere" to later retrieve it from "somewhere else" you seem to be looking for session functionality rather than viewstate... Also you cannot "create the same viewstate": what do you mean by this; viewstate is maintained (created, etc.) automatically by ASP.NET? I think you are mixing things up here (most probably viewstate and session). Maybe it would help if you describe what you are trying to achieve. – scherand Jun 11 '10 at 08:22
  • Did you check if enableviewstate is not set to false on your page or in web.config? – mamoo Jun 11 '10 at 08:24
  • 2
    I did not (yet) completely understand what you are trying to achieve. **But I think I might be able to answer your question about why `workFlow` is null**. The "problem" is that `GetEntityFromControls()` is "inside" `Workflow.aspx` (would that rather be `Workflow.ascx` maybe?). So the `ViewState` object you access is **not** the one of `Page`. So strictly speaking `ViewState["WorkFlow"]` is not null, but not defined/available (there is no entry called "WorkFlow" in the `ViewState` object since noone ever put one in there). – scherand Jun 11 '10 at 09:10
  • since Workflow.ascx is a usercontrol inside page and when page is rendered,they will be a single unit.So according to you,viewstate will be different for page and usercontrol. – Rohit Raghuvansi Jun 11 '10 at 09:43

4 Answers4

42

Scherand is very correct here. I'd like to add to what he has brought to the table.

Every control that derives from System.Web.UI.Control has the ViewState property. Under-the-hood the property is a StateBag collection. Every instance of a Control has its own StateBag for ViewState, so as Scherand mentioned, ViewState is unique to the control. When the page gets rendered, the entire Control tree of the Page is iterated, all ViewState collections are merged into a tree-like structure and that final structure is serialized to a string and rendered to the page.

Because the ViewState property is marked as protected, you can't get to the Page's ViewState from your User Control without the use of reflection.

But, in all honesty, you should abandon the use of ViewState as a data storage medium. Here are some reasons why:

  1. ViewState gets rendered and output to the client browser. Maintaining data objects in the collection bloats your Page's output.
  2. Unless you have encryption enabled on your ViewState, the encoded string that is rendered to the client browser can be decoded manually and simply anyone can access the content of your data objects. This is a rather significant security vulnerability.

It really sounds like all you want to do is share data between your Page and User Controls. The best way to share data between controls is to make use of the "Items" collection (which is a property of the HttpContext class). The collection is a Hashtable and can be accessed from your Page and User Controls like so:

Context.Items["Workflow"] = workflowInstance;

The best part of using this technique is that it doesn't incur any additional overhead or bloat the Page output. The Items collection exists in the context of a single HTTP request. This means that when your request is done and your Page's output has been rendered to the client browser, the Items collection is cleared from server memory. It's the ideal medium for temporary data storage within ASP.NET.

Now, if you want your data objects to remain accessible for more than just the current request, you'd be better off storing the objects in Session.

  • what about on postback? My code: Context.Items["dtCountryRecords"] = dtCountry; But when i access it first time it gives me correct values but on postback returns null in usercontrol pageload event. – user1254053 May 14 '15 at 11:34
  • 1
    The "Items" collection will not survive a Postback. Look to the second from last paragraph of my answer above for more details on that. If you want a medium that will survive Postbacks you'll need to look to either the "Session" or "Cache" collections. – peanutbutter_lou Jun 01 '15 at 16:22
  • In regards to the [comment above](http://stackoverflow.com/questions/3020674/why-cant-i-access-page-viewstate-in-usercontrol#comment49226927_3023315), bear in mind that the session *can* be lost between post-backs, so there is *no* guarantee the information will be there – freefaller Aug 24 '15 at 13:11
5

I still do not grok everything here (see my comments above). But I am pretty sure you are misunderstanding ViewState.

ViewState is per control, not per request or session or whatever.

In your example, consider some other control (e.g. a standard ASP.NET control) that for some reason decided to put something with a "name" of WorkFlow into viewstate. If what you are trying to do would work, this object would overwrite yours (or the other way around, yours would be overwritten by the other one).

Or am I missing something?

Maybe reading TRULY Understanding ViewState could help you understand what viewstate is/how it works (yes, I really like this article, this is why I keep posting that link).

scherand
  • 2,298
  • 20
  • 27
1

On postback did you create the control? If the code behind hasn't created the ctrl then it won't know about it.

only applicable if this is a generated control. You may need to post code and more info to get a propper answer.

Viewstate is a monster which is why a lot of us are going to MVC.

griegs
  • 22,624
  • 33
  • 128
  • 205
1

the page viewstate is a different statebag from the viewstate that the usercontrol can access. each control has their own private viewstate. So you cannot directly access the page viewstate from a usercontrol code-behind.

you could expose viewstate values with properties or methods and then call those properties/methods

marut
  • 11
  • 1