I have an enum like this:
public enum PaymentType
{
Self=1,
Insurer=2,
PrivateCompany=3
}
And I am showing it as select box opt
You can write an extension method like this:
public static System.Web.Mvc.SelectList ToSelectList(this TEnum obj)
where TEnum : struct, IComparable, IFormattable, IConvertible // correct one
{
return new SelectList(Enum.GetValues(typeof(TEnum)).OfType()
.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)
Here is a working Demo Fiddle of Enum binding with DropDownListFor