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

前端 未结 6 1700
伪装坚强ぢ
伪装坚强ぢ 2020-12-30 16:01

In my MVC 3 Razor app, I have a Model with an enum..

Model Example:

public class EmployeeModel
{
 public enum Title
 {
  Accountant = 111,
  Sales =          


        
6条回答
  •  南方客
    南方客 (楼主)
    2020-12-30 16:31

    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

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

提交回复
热议问题