Get Enum value to show on Dropdownlist Asp.Net MVC

前端 未结 3 1156
傲寒
傲寒 2020-12-20 10:03

I have an enum like this:

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

And I am showing it as select box opt

相关标签:
3条回答
  • 2020-12-20 10:28

    There is an extension method in MVC5 called SelectExtensions.EnumDropDownListFor which will generate the drop down list for you and bind the response back to an enum property in your model.

    0 讨论(0)
  • 2020-12-20 10:43
    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());
    }
    
    0 讨论(0)
  • 2020-12-20 10:47

    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

    0 讨论(0)
提交回复
热议问题