views:

104

answers:

1

Setup
Using: Visual Web Developer 2010 Express.
Language: C#.
Target Framework: .NET Framework 4.
ViewState: I have disabled ViewState in the Web.Config - i.e. <configuration><system.web><pages enableViewState="false" />.

Problem
I have an ASP.NET page with a standard DropDownList control.
I have set EnableViewState="true" and ViewStateMode="Enabled" on the DropDownList.
I'm using data binding in the code-behind to populate the control (this works fine).
Data binding happens in a call from Page_PreRender, on both initial load and post-back.
In a call from a Button Click event handler (i.e. before the Page_PreRender) I am trying to read from the SelectedValue property of the DropDownList.
The problem is: all I ever receive is a zero-length-string ("") value and inspection of the object indicates the control contains to values.

Solution
Ensure EnableViewState="true" is set within the <%@ Page %> directive on the page containing the DropDownList.

Alternatively, you could create an extension method for the DropDownList that reads the value from the HttpRequest collection.
e.g.

public static string GetSelectedValue(this System.Web.UI.WebControls.DropDownList listBox)
{
  return HttpContext.Current.Request[listBox.ClientID];
}
A: 

you are correct (aside from UniqueID as Jason pointed out)

but why are you disabling viewstate globally? it is one of the great perks of asp.net and necessary for lots of functionality in your pages. It isn't that bad for most controls so no reason to fear it.

You want to keep an eye on controls that generate a lot of markup (such as grids) and definitely disable it on those.

Just turn on Trace in your Page directive, and you will see how much viewstate is being used by each node on your control tree.

Sonic Soul
RE disabling ViewState - it's a combination of factors but largely personal preference. I've been developing since before ViewState was around and still prefer to work close to the metal and without "magic". I also prefer an "additive" approach to development (add as required) rather than reductive (remove as required).
Jason Snelders