DropdownListFor selected value not selecting in the rendered html

asp.net-mvc, asp.net-mvc-3, c#

Solution

I'm actually running into this exact problem myself and discovered that the DropDownListFor (and DropDownList) helpers are a little too smart for their own good.

Even if you pass in a set of `SelectListItem` with one of them `Selected = true`, the helper will actually evaluate your model, do a `Convert.ToString()` on it, and attempt to match the value. If it doesn't find the value it will select nothing.

Personally I believe this is a major mistake in MVC, one that they do not appear to be correcting in MVC4. It is a completely bogus assumption on their part that that the `ToString()` method of an object would match the value (rather than the display text) in a dropdown.

edit: as for ways to fix this...

- Change your `ToString()` method to return the value and figure out a different way to get your display text.

- Since you're using an enum, you could just the string version for both your value and your display text. It will still bind fine.

- Build your own dropdown

Problem

I have an extension method that I'm trying to use where you can use an enum property to create a dropdown list, and set the selected item: ``` public enum DefaultEnumSelectItemOptions { AddDefaultItemIfEnumIsZero, ZeroEnumIsDefaultItem } public static SelectList ToSelectList(this object enumObj, DefaultEnumSelectItemOptions option = DefaultEnumSelectItemOptions.AddDefaultItemIfEnumIsZero) { var asEnum = Enum.Parse(enumObj.GetType(), enumObj.ToString()); var values = Enum.GetValues(enumObj.GetType()); var dataItems = new List<Tuple<string, int>>(); dataItems.Add(new Tuple<string, int>("Select One", -1)); for (int i = 0; i < values.Length; i++) { int enumValue = (int)values.GetValue(i); if (enumValue == 0) { if (option != DefaultEnumSelectItemOptions.AddDefaultItemIfEnumIsZero) { dataItems.Add(new Tuple<string, int>(values.GetValue(i).ToString(), enumValue)); } } else { dataItems.Add(new Tuple<string, int>(values.GetValue(i).ToString(), enumValue)); } } var selectedItemValue = (int)enumObj; if (selectedItemValue == 0 && option == DefaultEnumSelectItemOptions.AddDefaultItemIfEnumIsZero) { selectedItemValue = -1; } return new SelectList(dataItems, "Item2", "Item1", selectedItemValue); } ``` A model looks like this: ``` public enum PropertyTypes { Unknown=0, Vehicle, Other } [DataContract] public class Property : ClaimEntity { [DataMember] public PropertyTypes PropertyType { get; set; } public Property() { this.PropertyType = PropertyTypes.Vehicle; } } ``` Finally the view looks like this: ``` @Html.DropDownListFor(m => m.PropertyType, Model.PropertyType.ToSelectList()) ``` When I set a breakpoint in the extension method, it appears to be correct, but the selected option is not appearing in the html. What am I doing wrong? edit I changed it to use the `SelectListItem` as suggested, however I still am not seeing the value selecting:

Original source