In my MVC 3 Razor app, I have a Model with an enum..
Model Example:
public class EmployeeModel
{
public enum Title
{
Accountant = 111,
Sales = 222,
Production = 333
}
[Required]
public string Name {get; set;}
[Required]
public Title JobTitle {get; set;}
}
In my View I would like to use the Html helpers to build an Html Form...
View Example:
@model ..Models.EmployeeModel
@using (Html.BeginForm())
{
@Html.LabelFor(m => m.Name)
@Html.TextBoxFor(m => m.Name)
<br>
@Html.LabelFor(m => m.JobTitle)
@Html.DropDownListFor(m => m.JobTitle, ??How do I get Title enum values??)
<br>
<input type="submit />
}
The output of the DropDownListFor that I trying to achieve would look like this: Note the option values match the initialized values of the enum
<select name="JobTitle">
<option value="-1">Choose a Job Title</option>
<option value="111">Accountant</option>
<option value="222">Sales</option>
<option value="333">Production</option>
</select>
How do I get the DropDownListFor<> helper to create a select/option element based on the Title enum of the Model?
Also, is it possible to have the DropDownListFor<> helper to add an extra (that is not part of the enum) similar to the "Choose a Job Title" option in the example above?
I just stumbled on this StackO question/answer - not only is my question here an exact duplicate, but the answer given by Mike McLaughlin is the best solution I've seen for using
DropdownListFor<>
withEnums
. Specifically, Mike points us to a solution that he found by Morgan LeroiMorgan's quick solution is:
But, Morgan has made an Extension that makes the implementation of the
DropDownListFor<>
with enums even more compact. You can download Morgan's Visual Studio Solution here.That said, I think we should close this question as it's an exact duplicate.
I solved it with this extension:
(I found the extension on SO, but without the default value)
Here's a way using Html Helpers:
Model
View
HTML Output
You could possibly get a
String[]
with the names of the enum values and create a dropdown from that. In your view model, add a propertyTitles
of typeSelectListItem
and add the enum values and names to that. You can get the names and values through theSystem.Enum
type.It's kind of ugly, but it'll work.
Here is the solution
Add ViewBag name in DropDownList :
An encapsulated HTML Helper Extension is available here :
http://www.spicelogic.com/Journal/ASP-NET-MVC-DropDownListFor-Html-Helper-Enum-5
the source code snapshot:
You can download the full source code of the project from the link.