mvc4中的下拉列表中的枚举值
本文关键字:枚举 下拉列表 mvc4 | 更新日期: 2023-09-27 18:18:45
如何在mvc4中使用enum值创建下拉列表
我有一个类Language.cs
public enum Language {
English = 0
}
属性是
public Language Language { get; set; }
我如何通过下拉列表调用我的视图
你可以有一个视图模型:
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
所示。这就行了:
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)