Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to use MVC Html Helper .DropDownListFor<> with an Enum

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?

like image 563
Jed Avatar asked May 26 '11 23:05

Jed


1 Answers

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 property Titles of type SelectListItem and add the enum values and names to that. You can get the names and values through the System.Enum type.

var defaultItem = new SelectListItem();
defaultItem.Value = -1;
defaultItem.Text = "Choose a title";
defaultItem.Selected = true;
model.TitleSelectItems.add(defaultItem);

String[] names = System.Enum.GetNames(typeof(Title));
Int[] values = System.Enum.GetValues(typeof(Title));

for (int i = 0; i<names.Length; i++)
{
    var item = new SelectListItem();
    item.Text = names[i];
    item.Value = values[i];
    model.TitleSelectItems.Add(item);
}

It's kind of ugly, but it'll work.

like image 146
Tomas Aschan Avatar answered Sep 21 '22 14:09

Tomas Aschan