在下拉列表中使用ViewData和viewcode列出枚举值
本文关键字:viewcode 枚举 ViewData 下拉列表 | 更新日期: 2023-09-27 18:18:55
如何在ASP中使用enum值创建下拉列表?Net MVC 4?
有一个Language
枚举:
public enum Language
{
English = 0,
spanish = 2,
Arabi = 3
}
我的属性是:
public Language Language { get; set; }
我的控制器动作是这样的:
[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这个帮助可以这样使用:
控制器中:
//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();
}
}