c# - 使用枚举和 Entity Framework 脚手架从模型创建下拉列表?

标签 c# asp.net-mvc entity-framework model-view-controller enums

考虑到模型具有枚举属性, Entity Framework 是否有办法自动在 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 方法获取枚举值。将数据传递到 View 的一种选择是使用 ViewBag:

var majorList = Enum.GetValues(typeof(MajorList))
                    .Cast<MajorList>()
                    .Select(e => new SelectListItem
                         {
                             Value =e.ToString(),
                             Text = e.ToString()
                         });
ViewBag.MajorList=majorList;

或者将其添加为 ViewModel 中的属性,以防您以这种方式工作。

稍后在您的 View 中,您可以使用 DropDownList,如下所示:

@Html.DropDownListFor(model => model.Major, ViewBag.MajorList, htmlAttributes: new { @class = "form-control" })

根据这个post中的解决方案以下也应该有效:

@Html.DropDownListFor(model =>model.Major, new SelectList(Enum.GetValues(typeof(MajorList))))

另一个解决方案可以创建您自己的 EnumDropDownListFor 帮助程序(如果您想了解有关此类解决方案的更多信息,请查看此 page):

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
            );
    }
}

这样,您可以执行我在答案开头建议的相同操作,只需引用使用扩展声明静态类的 namespace :

@using yourNamespace 
//...

 @Html.EnumDropDownListFor(model => model.Major, htmlAttributes: new { @class = "form-control" })

关于c# - 使用枚举和 Entity Framework 脚手架从模型创建下拉列表?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/35638727/

相关文章:

c# - C# 中的 Action 委托(delegate)

c# - 尝试在 View 中使用模型时出现 MVC 错误

c# - 异常 : object instance has been disposed and can no longer be used for operations that requires a connection

c# - 如何为 linq 查询创建一个类 (EF)

c# - 在运行时选择实体连接字符串

c# - 在哪里练习Lambda函数?

c# - 移动列时 UltraGrid VisiblePosition 不会改变

javascript - 为什么我的 AJAX 错误没有返回 Webmethod 异常?

c# - 制作一些 OnIdiom 和 OnPlatform StaticResource

c# - ASP.NET MVC RC(刷新)中的 Html.DropDownList 未预选项目