简体   繁体   中英

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:

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. 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:

<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

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属性。

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

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