[英]enum values in drop down list using ViewData and th viewcode to list it?
如何使用ASP.NET MVC 4中的枚舉值創建下拉列表?
我有一個Language
枚舉:
public enum Language
{
English = 0,
spanish = 2,
Arabi = 3
}
我的財產是:
public Language Language { get; set; }
我的Controller動作如下所示:
[HttpPost]
public ActionResult Edit(tList tableSheet)
{
return RedirectToAction("Index");
}
如何通過使用ViewData[]
的下拉列表調用我的視圖?
這將返回
Enum.GetNames(typeOf(Language ))
English
spanish
Arabi
還有這個
Enum.GetValues(typeOf(Language ))
1,2,3
您可以查看語言列表:
ViewBeg.Languages = Enum.GetNames(typeOf(Language)).ToList();
我知道我已經遲到了派對但是......看看我創建的助手班就是這么做的......
http://jnye.co/Posts/4/creating-a-dropdown-list-from-an-enum-in-mvc-and-c%23
這個helpe可以使用如下:
在控制器中:
//If you don't have an enum value use the type
ViewBag.DropDownList = EnumHelper.SelectListFor<Language>();
//If you do have an enum value use the value (the value will be marked as selected)
ViewBag.DropDownList = EnumHelper.SelectListFor(myEnumValue);
在視圖中
@Html.DropDownList("DropDownList")
幫手:
public static class EnumHelper
{
//Creates a SelectList for a nullable enum value
public static SelectList SelectListFor<T>(T? selected)
where T : struct
{
return selected == null ? SelectListFor<T>()
: SelectListFor(selected.Value);
}
//Creates a SelectList for an enum type
public static SelectList SelectListFor<T>() where T : struct
{
Type t = typeof (T);
if (t.IsEnum)
{
var values = Enum.GetValues(typeof(T)).Cast<enum>()
.Select(e => new { Id = Convert.ToInt32(e), Name = e.GetDescription() });
return new SelectList(values, "Id", "Name");
}
return null;
}
//Creates a SelectList for an enum value
public static SelectList SelectListFor<T>(T selected) where T : struct
{
Type t = typeof(T);
if (t.IsEnum)
{
var values = Enum.GetValues(t).Cast<Enum>()
.Select(e => new { Id = Convert.ToInt32(e), Name = e.GetDescription() });
return new SelectList(values, "Id", "Name", Convert.ToInt32(selected));
}
return null;
}
// Get the value of the description attribute if the
// enum has one, otherwise use the value.
public static string GetDescription<TEnum>(this TEnum value)
{
FieldInfo fi = value.GetType().GetField(value.ToString());
if (fi != null)
{
DescriptionAttribute[] attributes =
(DescriptionAttribute[])fi.GetCustomAttributes(
typeof(DescriptionAttribute),
false);
if (attributes.Length > 0)
{
return attributes[0].Description;
}
}
return value.ToString();
}
}
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.