I have a Enum
called CityType
public enum CityType
{
[Description("Select City")]
Select = 0,
[Description("A")]
NewDelhi = 1,
[Description("B")]
Mumbai = 2,
[Description("C")]
Bangalore = 3,
[Description("D")]
Buxar = 4,
[Description("E")]
Jabalpur = 5
}
Generate List from Enum
IList<SelectListItem> list = Enum.GetValues(typeof(CityType)).Cast<CityType>().Select(x => new SelectListItem(){
Text = EnumHelper.GetDescription(x),
Value = ((int)x).ToString()
}).ToList();
int city=0;
if (userModel.HomeCity != null) city= (int)userModel.HomeCity;
ViewData["HomeCity"] = new SelectList(list, "Value", "Text", city);
Bind on .cshtml
@Html.DropDownList("HomeCity",null,new { @style = "width:155px;", @class = "form-control" })
EnumHelper GetDescription Class to get Description of Enum
If you want to pass the selected value of your dropdown list into your controller, just add a string parameter with the name drpFields (same as the first parameter of your DropDownList method) into your temp action method. Hope it will help you to fix your problem.
I blogged about this very subject whereby I create an EnumHelper
to help with this common task.
http://jnye.co/Posts/4/creating-a-dropdown-list-from-an-enum-in-mvc-and-c%23
In your controller:
//If you don't have an enum value use the type
ViewBag.DropDownList = EnumHelper.SelectListFor<MyEnum>();
//If you do have an enum value use the value (the value will be marked as selected)
ViewBag.DropDownList = EnumHelper.SelectListFor(MyEnum.MyEnumValue);
In your View:
@Html.DropDownList("DropDownList")
@* OR *@
@Html.DropDownListFor(m => m.Property, ViewBag.DropDownList as SelectList, null)
The helper class:
public static class EnumHelper
{
// Get the value of the description attribute if the
// enum has one, otherwise use the value.
public static string GetDescription<TEnum>(this TEnum value)
{
var fi = value.GetType().GetField(value.ToString());
if (fi != null)
{
var attributes = (DescriptionAttribute[])fi.GetCustomAttributes(typeof(DescriptionAttribute), false);
if (attributes.Length > 0)
{
return attributes[0].Description;
}
}
return value.ToString();
}
/// <summary>
/// Build a select list for an enum
/// </summary>
public static SelectList SelectListFor<T>() where T : struct
{
Type t = typeof(T);
return !t.IsEnum ? null
: new SelectList(BuildSelectListItems(t), "Value", "Text");
}
/// <summary>
/// Build a select list for an enum with a particular value selected
/// </summary>
public static SelectList SelectListFor<T>(T selected) where T : struct
{
Type t = typeof(T);
return !t.IsEnum ? null
: new SelectList(BuildSelectListItems(t), "Text", "Value", selected.ToString());
}
private static IEnumerable<SelectListItem> BuildSelectListItems(Type t)
{
return Enum.GetValues(t)
.Cast<Enum>()
.Select(e => new SelectListItem { Value = e.ToString(), Text = e.GetDescription() });
}
}
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With