C# 使用枚举和实体框架脚手架从模型创建下拉列表?
鉴于模型具有枚举属性,EntityFramework是否有办法自动在HTML中创建下拉列表?这是我目前在模型中拥有的内容,但当运行我的项目时,只有一个文本框而不是下拉框C# 使用枚举和实体框架脚手架从模型创建下拉列表?,c#,asp.net-mvc,entity-framework,model-view-controller,enums,C#,Asp.net Mvc,Entity Framework,Model View Controller,Enums,鉴于模型具有枚举属性,EntityFramework是否有办法自动在HTML中创建下拉列表?这是我目前在模型中拥有的内容,但当运行我的项目时,只有一个文本框而不是下拉框 public enum MajorList { Accounting, BusinessHonors, Finance, InternationalBusiness, Management, MIS, Marketing, SupplyChainManagement, STM } [Display(Name = "Major")
public enum MajorList { Accounting, BusinessHonors, Finance, InternationalBusiness, Management, MIS, Marketing, SupplyChainManagement, STM }
[Display(Name = "Major")]
[Required(ErrorMessage = "Please select your major.")]
[EnumDataType(typeof(MajorList))]
public MajorList Major { get; set; }
您可以为以下内容更改
@Html.EditorFor
:
@Html.EnumDropDownListFor(model => model.Major, htmlAttributes: new { @class = "form-control" })
更新:
正如@StephenMuecke在其评论中确认的那样,EnumDropDownListFor仅在MVC 5.1中可用,因此另一种解决方案可能是使用
enum.GetValues
方法获取枚举值。将该数据传递到视图的一个选项是使用ViewBag
:
var majorList = Enum.GetValues(typeof(MajorList))
.Cast<MajorList>()
.Select(e => new SelectListItem
{
Value =e.ToString(),
Text = e.ToString()
});
ViewBag.MajorList=majorList;
根据本节中的解决方案,以下各项也应起作用:
@Html.DropDownListFor(model =>model.Major, new SelectList(Enum.GetValues(typeof(MajorList))))
另一个解决方案可以是为helper创建您自己的
EnumDropDownList(如果您想了解有关此类解决方案的更多信息,请选中此选项):
谢谢你的意见!我收到错误“'System.Web.Mvc.HtmlHelper不包含EnumDropDownListFor的定义,并且找不到扩展方法EnumDropDownListFor”EnumDropDownListFor()
仅在Mvc 5.1或更高版本中可用。
@Html.DropDownListFor(model =>model.Major, new SelectList(Enum.GetValues(typeof(MajorList))))
using System.Web.Mvc.Html;
public static class HTMLHelperExtensions
{
public static MvcHtmlString EnumDropDownListFor<TModel, TEnum>(this HtmlHelper<TModel> htmlHelper, Expression<Func<TModel, TEnum>> expression)
{
ModelMetadata metadata = ModelMetadata.FromLambdaExpression(expression, htmlHelper.ViewData);
IEnumerable<TEnum> values = Enum.GetValues(typeof(TEnum)).Cast<TEnum>();
IEnumerable<SelectListItem> items =
values.Select(value => new SelectListItem
{
Text = value.ToString(),
Value = value.ToString(),
Selected = value.Equals(metadata.Model)
});
return htmlHelper.DropDownListFor(
expression,
items
);
}
}
@using yourNamespace
//...
@Html.EnumDropDownListFor(model => model.Major, htmlAttributes: new { @class = "form-control" })