Search code examples
asp.netformsviewstate

Why does DropDownList.SelectedValue is relied on viewstate?


If I set on my page : EnableViewState="true" ViewStateMode="Disabled" - Then - the Viewstate is disable for the page ( unless override...)

Then, trying to read from (assuming the control has been populated in the last dump to the screen and a value is selected):

MyDDL.SelectedValue will yield ""

That's because of disabled viewstate :

But my question is at a higher level :

  • If it's all about a form value (which I still can get from Request.Form[MyDDL.UniqueID]) - and we're talking about an input which doesn't need anything to save its value.

  • Why does the DropDownList property named (SelectedValue) Is relied on ViewState ?

p.s. the TextBox onchangeevent does rely on viewstate although the control is an input (which doesnt need viewstate) - it saves the value of the text and then it compare it when postback.But it only relies on viewstate when you set onchange event ( and autopostback)


Solution

  • SUMMARY: If you want the control to work without ViewState, you need to populate/bind the Items collection on every postback. I recommend doing it in the Page_Init event (i.e. OnInit method).

    First off, I always recommend this this awesome article: TRULY Understanding ViewState.

    The SelectedValue doesn't require ViewState. Looking at the code for ListControl, which DropDownList inherits from, we see the code:

    public virtual string SelectedValue
    {
      get
      {
        int selectedIndex = this.SelectedIndex;
        if (selectedIndex >= 0)
          return this.Items[selectedIndex].Value;
        else
          return string.Empty;
      }
    

    The important thing to take away from this code is that the Items list must be populated to get the SelectedValue.

    If you utilize ViewState, the Items collection is persisted to / loaded from ViewState, which allows the SelectedValue property to work without rebinding the control.