Why does DropDownList.SelectedValue is relied on viewstate?

后端 未结 4 483
南方客
南方客 2021-02-08 22:01

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

The

4条回答
  •  既然无缘
    2021-02-08 22:23

    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.

提交回复
热议问题