I’m pulling my hair out here. I’m using the DropDownListFor HTML helper in MVC3 with Enums like so:
@Html.DropDownListFor(model => model.Title, Enum.GetValues(typeof(ICS_Signup_Form.Models.Titles)).Cast<ICS_Signup_Form.Models.Titles>().Select(x => new SelectListItem { Text = x.ToString().ToFriendlyString(), Value = x.ToString() }), new { @class = "styled" })
My enum looks like so: public enum Titles { Mr, Dr, Miss, Mrs, Ms, Other };
If Model.Title equals “Other” then the drop down list doesn’t select this value, there’s no selected="selected" in the HTML. I’ve tried adding the property Selected to SelectListItem: Selected = (x.ToString() == Model.Title) and the expression works fine when I’m stepping through my code, as expected but the selected value is always “Mr” (the first in the list).
What’s even weirder this works perfectly fine (as do the other 7 drop down boxes I have in my project):
@Html.DropDownListFor(model => model.BusinessStatus, Enum.GetValues(typeof(ICS_Signup_Form.Models.BusinessTypes)).Cast<ICS_Signup_Form.Models.BusinessTypes>().Select(x => new SelectListItem { Text = x.ToString().ToFriendlyString(), Value = x.ToString() }), new { @class = "styled" })
With the enum: public enum BusinessTypes { Charity, Government, Limited, LLP, Partnership, PLC, SoleTrader };
The difference? None.. Any ideas?
tldr; change the name of your DropDownList to something else
I had the same problem (albeit in ASPX engine, which I believe doesn’t make any difference in this case). Here’s how to repro it:
the codebehind (note “Selected = true” in the second item):
the ASPX code:
It reproes: you can see that the first item gets selected automatically and neither of the items have the “selected” option in HTML. Here’s the generated HTML which reproes it:
Solution: Turns out some of the element names cause the ASPX rendering engine to behave differently. In my case, I just changed the DropDownList name from “team” to “defaultteam” — and it started working:
Here’s WORKING ASPX code:
and here is the HTML generated by it: