Welcome to OStack Knowledge Sharing Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
610 views
in Technique[技术] by (71.8m points)

c# - 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?

See Question&Answers more detail:os

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome To Ask or Share your Answers For Others

1 Answer

0 votes
by (71.8m points)

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


与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome to OStack Knowledge Sharing Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

...