1

Ok, so this is an issue that has bothered me since the first time I started playing with MVC around 3 years ago. Binding to dropdownlists has always been a pain in the arse but there is a neat way to do it for enums by doing this:

 @Html.DropDownListFor(model => model.Type, new SelectList(Enum.GetValues(typeof(mediaZone.Common.Models.AssetType)), Model.Type))

Great, but the only problem is that that solution will output something like this:

<select id="Type" name="Type">
    <option>Image</option>
    <option selected="selected">Video</option>
    <option>Website</option>
</select>

What I would like to do is output something like this:

<select id="Type" name="Type">
    <option value="1">Image</option>
    <option value="2" selected="selected">Video</option>
    <option value="3">Website</option>
</select>

We are on version 5 now of MVC, you would think that many many many people have had this issue and don't want to write code to fix it. I really hope someone out there has a one line solution to this niggling issue of mine :)

Cheers, /r3plica

r3plica
  • 13,017
  • 23
  • 128
  • 290
  • Have you visted http://stackoverflow.com/questions/4656758/mvc3-razor-dropdownlistfor-enums – Satpal Oct 04 '13 at 15:07
  • not what I am looking for. I don't want a helper class, I don't even want to write any more code that one line. I know I "could" write a helper class myself, but surely, something this simple should just be a part of MVC.... – r3plica Oct 04 '13 at 15:42
  • So... you need to know if there is a 1 line solution to your problem... that is all your question? Then: NO. The line counting thing, back to adolescence time :) – Romias Oct 07 '13 at 14:26
  • seems strange that I can create a dropdown list based off my enum in one line, but I can't specify a default value as well..... – r3plica Oct 08 '13 at 14:55

1 Answers1

1

Do it in the controller, it is just a foreach for your enum items, returning a collection with 2 values instead of just the name.

Then... in your view you can get a one line of code, far cleaner that the one you have now:

@Html.DropDownListFor(model => model.Type, Model.MySelectList)

Other benefits of doing the foreach, is that you could need internationalization in the names of each Enum item, so you could do the translation during the foreach.

Romias
  • 13,783
  • 7
  • 56
  • 85