SelectExtensions.DropDownList resets SelectListItem's Selected property

1.1k views Asked by At

I found a weird behavior when using the SelectExtension's DropDownList method. I create a IEnumerable<SelectListItem> where one of them has it's Selected property is set to 'true'. However, when I pass it to the following method, the Selected property is reset to 'false' and thus the dropdown control does not have the proper item selected.

public static MvcHtmlString DropDownList(this HtmlHelper htmlHelper, string name, IEnumerable selectList);

I have even tried using the SelectList class and specified the SelectedValue property but still the proper <option> tag is not being selected.

Any ideas on how I might maintain the selected value?

WROTE HACK BUT WOULD PREFER SOLUTION

Below is a code hack to change the selected option before using the emitted Html from MVC. I don't like this solution, but I don't know how else to go about it.

// the following is a hack due to a precived MVC 3 bug
var html = SelectExtensions.DropDownList(helper, propertyName, source).ToHtmlString();
html = html.Replace("selected=\"selected\"", string.Empty);
html = html.Replace(string.Format("value=\"{0}\"", source.SelectedValue), string.Format("value=\"{0}\" selected=\"selected\"", source.SelectedValue));
1

There are 1 answers

0
Chris Smith On

The Framework is ignoring your selected value because it looks into the html.ViewData and finds a key matching the name of your drop down (propertyName in this case) and tries to use the value there instead.

One solution is to alter the html.ViewData before you create your DropDownList. In your case, something like this:

html.ViewData[propertyName] = source.SelectedValue;

A more generic example:

html.ViewData['name of your DDL'] = 'The real value you want selected';