如何使用mvc4中的枚举值创建下拉列表
我有一个类Language.cs
public enum Language {
English = 0
}
我的财产是
public Language Language { get; set; }
如何通过下拉列表调用我的视图
答案 0 :(得分:6)
你可以有一个视图模型:
public class MyViewModel
{
public Language SelectedLanguage { get; set; }
public IEnumerable<SelectListItem> Languages
{
get
{
var languages =
from l in Enum.GetValues(typeof(Language))
select new { ID = (int)d, Name = d.ToString() };
return new SelectList(languages , "ID", "Name", this.SelectedLanguage);
}
}
}
然后在你看来:
@Html.DropDownListFor(x => x.SelectedLanguage, Model.Languages)
另一种可能性是编写一个自定义帮助器,它将封装此逻辑,如this blog post
所示。
答案 1 :(得分:2)
这将完成这项工作:
public enum Language
{
English,
French,
Spanish
}
public static class Enum
{
public static IEnumerable<T> GetItems<T>()
{
return System.Enum.GetValues(typeof(T)).Cast<T>();
}
}
public class ViewModel
{
public Language Language
{
get;
set;
}
public IEnumerable<SelectListItem> Languages
{
get
{
return Enum.GetItems<Language>().Select(x => new SelectListItem() { Text = x.ToString(), Value = x.ToString() });
}
}
}
HTML:
@model ViewModel
@Html.DropDownListFor(a => a.Language, Model.Languages)