【问题标题】:Get Enum value to show on Dropdownlist Asp.Net MVC获取枚举值以显示在 Dropdownlist Asp.Net MVC 上
【发布时间】:2015-03-02 10:26:23
【问题描述】:

我有一个这样的枚举:

public enum PaymentType
{
    Self=1,
    Insurer=2,
    PrivateCompany=3
}

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

List<Patient.PaymentType> paymentTypeList =
    Enum.GetValues(typeof (Patient.PaymentType)).Cast<Patient.PaymentType>().ToList();
    ViewBag.PaymentType = new SelectList(paymentTypeList);

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

【问题讨论】:

  • 您不一定需要,因为DefaultModelBinder 会在您回发时绑定到字符串值,但these answers 显示了一些方法来做到这一点。
  • 只需将其转换为int,它将为您提供int 值。
  • 您是否尝试过搜索? stackoverflow.com/questions/388483/… 等等。

标签: c# asp.net asp.net-mvc enums


【解决方案1】:

你可以这样写一个扩展方法:

 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");

}

并在实际中像这样使用它:

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

     return View();
}

在视图中:

@Html.DropDownListFor(m=>m.SomeProperty,ViewBag.EnumList as SelectList)

呈现的 HTML:

<select id="EnumDropDown" name="EnumDropDown">
<option value="1">Self</option>
<option value="2">Insurer</option>
<option value="3">PrivateCompany</option>
</select>

这是working Demo Fiddle of Enum binding with DropDownListFor

【讨论】:

  • 请说明如何使用这个扩展。以便对其他人也有用
【解决方案2】:
public enum PaymentType
{
        Self=1,
        Insurer=2,
        PrivateCompany=3
}

获取自我价值:

int enumNumber = (int)PaymentType.Self; //enumNumber = 1

示例:

getEnum(PaymentType.Self);

private void getEnum(PaymentType t)
{
            string enumName = t.ToString();
            int enumNumber = (int)t;
            MessageBox.Show(enumName + ": " + enumNumber.ToString());
}

【讨论】:

    【解决方案3】:

    MVC5 中有一个名为 SelectExtensions.EnumDropDownListFor 的扩展方法,它将为您生成下拉列表并将响应绑定回模型中的枚举属性。

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 1970-01-01
      • 2015-08-31
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2013-03-30
      • 1970-01-01
      相关资源
      最近更新 更多