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

前端 未结 6 1711
伪装坚强ぢ
伪装坚强ぢ 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:35

    I solved it with this extension:

    public static SelectList ToSelectListWithDefault(this TEnum enumObj, string defValue, string defText) where TEnum : IConvertible
    {
        var values = new List();
        var defItem = new SelectListItem() { Value = defValue, Text = defText };
        values.Add(defItem);
        foreach (TEnum e in Enum.GetValues(typeof(TEnum)))
        {
            values.Add(new SelectListItem() { Value = e.ToInt16(null).ToString(), Text = e.ToString() });
        }
    
        return new SelectList(values, "Value", "Text", defItem);
    }   
    

    (I found the extension on SO, but without the default value)

提交回复
热议问题