简体   繁体   English

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

[英]Get Enum value to show on Dropdownlist Asp.Net MVC

I have an enum like this: 我有一个这样的枚举:

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

And I am showing it as select box options like this inside Controller: 我将其显示为Controller内部的选择框选项:

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

Here I can see that only the string part (example "Self") of the enum is going to the front end, so I won't get the value (example "1") of enum in my dropdown. 在这里,我看到只有枚举的字符串部分(例如“ Self”)进入前端,因此在下拉列表中我不会得到枚举的值(例如“ 1”)。 How can I pass text as well as value of enum to select list? 如何传递文本以及枚举值来选择列表?

You can write an extension method like this: 您可以编写如下扩展方法:

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

}

and in action use it like this: 并在操作中像这样使用它:

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

     return View();
}

and in View : 并在视图中:

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

Rendered HTML: 呈现的HTML:

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

Here is a working Demo Fiddle of Enum binding with DropDownListFor 这是使用DropDownListFor进行枚举绑定的演示演示小提琴

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

Get Self value: 获得自我价值:

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

Exemple: 例:

getEnum(PaymentType.Self);

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

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

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM