views:

1673

answers:

3

I have a drop down menu and on postback, I cannot get the selected value.

  • MasterPage EnableViewState = False
  • Content Page ViewState = true
  • DropdownList Control ViewState = true

Doesn't work

If I switch the Masterpage EnableViewState = true, it works, however the rest of the site really doesn't need view state so ideally I want it to be enabled.

The Databinding happens in the Page_Init Handler and there is a Page.IsPostBack clause in it.

Any ideas?

+5  A: 

There is only one Viewstate per page(aside from control state, which is stored in viewstate). If you turn it off at the Masterpage, it is turned off on the page.

Chris Ballance
So setting it in the Page itself does not override it?
TimLeung
The masterpage setting is overriding here and effectively Viewstate is turned off
Chris Ballance
+2  A: 

Chris is 100% correct. If you want to only maintain state on this one control you could subclass DropDown and add control state. This works irrespective of any ViewState settings.

Here is a Phil Haack tutorial on control state.

Andrew Hare
+1 for the Haacked tutorial
Chris Ballance
+1  A: 

I think you should be able to get the dropdownlist's selected value from the Form collection (without having to enable ViewState), e.g:

if (IsPostBack)
    string selectedValue = Request.Form["Id_of_the_DropDownList"];
M4N