使用枚举和实体框架基架从模型创建下拉列表
本文关键字:模型 创建 下拉列表 框架 枚举 实体 | 更新日期: 2023-09-27 18:36:11
鉴于模型具有枚举属性,实体框架有没有办法在 HTML 中自动创建下拉列表?这是我目前在我的模型中拥有的内容,但是在运行我的项目时,只有一个文本框而不是下拉列表!
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;
或者将其作为属性添加到您的 ViewModel 中,以防您以这种方式工作。
稍后在视图中,您可以使用如下DropDownList
:
@Html.DropDownListFor(model => model.Major, ViewBag.MajorList, htmlAttributes: new { @class = "form-control" })
根据这篇文章中的解决方案,以下内容也应该有效:
@Html.DropDownListFor(model =>model.Major, new SelectList(Enum.GetValues(typeof(MajorList))))
另一种解决方案可能是创建自己的EnumDropDownListFor
助手(如果您想阅读有关此类解决方案的更多信息,请查看此页面):
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" })