获取枚举值以显示在 Dropdownlist Asp.Net MVC 上

Ath*_*hul 0 c# asp.net asp.net-mvc enums

我有一个这样的枚举:

public enum PaymentType
{
    Self=1,
    Insurer=2,
    PrivateCompany=3
}
Run Code Online (Sandbox Code Playgroud)

我将它显示为 Controller 中这样的选择框选项:

List<Patient.PaymentType> paymentTypeList =
    Enum.GetValues(typeof (Patient.PaymentType)).Cast<Patient.PaymentType>().ToList();
    ViewBag.PaymentType = new SelectList(paymentTypeList);
Run Code Online (Sandbox Code Playgroud)

在这里我可以看到只有枚举的字符串部分(例如“Self”)进入前端,所以我不会在下拉列表中获得枚举的值(例如“1”)。如何将文本和枚举值传递给选择列表?

Ehs*_*jad 5

您可以编写这样的扩展方法:

 public static System.Web.Mvc.SelectList ToSelectList<TEnum>(this TEnum obj)
            where TEnum : struct, IComparable, IFormattable, IConvertible // correct one
 {

   return new SelectList(Enum.GetValues(typeof(TEnum)).OfType<Enum>()
              .Select(x =>
                    new SelectListItem
                    {
                        Text = Enum.GetName(typeof(TEnum), x),
                        Value = (Convert.ToInt32(x)).ToString()
                    }), "Value", "Text");

}
Run Code Online (Sandbox Code Playgroud)

并在行动中像这样使用它:

public ActionResult Test()
{
     ViewBag.EnumList = PaymentType.Self.ToSelectList();

     return View();
}
Run Code Online (Sandbox Code Playgroud)

并在视图中:

@Html.DropDownListFor(m=>m.SomeProperty,ViewBag.EnumList as SelectList)
Run Code Online (Sandbox Code Playgroud)

渲染的 HTML:

<select id="EnumDropDown" name="EnumDropDown">
<option value="1">Self</option>
<option value="2">Insurer</option>
<option value="3">PrivateCompany</option>
</select>
Run Code Online (Sandbox Code Playgroud)

这是一个使用 DropDownListFor 的 Enum 绑定工作演示小提琴