简体   繁体   English

使用enum和Entity Framework脚手架从模型创建下拉列表?

[英]Create a dropdown list from model using enum and Entity Framework scaffolding?

Is there a way for Entity Framework to automatically create a dropdown list in HTML given that the model has an enum property? 给定模型具有enum属性,实体框架是否可以通过HTML自动创建下拉列表? Here's what I currently have inside my model, but when running my project there's just a text box instead of a dropdown! 这是我当前在模型中拥有的内容,但是在运行项目时,只有一个文本框而不是下拉列表!

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

You could change your @Html.EditorFor for the following: 您可以为以下内容更改@Html.EditorFor

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

Update: 更新:

As @StephenMuecke confirmed in his comment EnumDropDownListFor is only available in MVC 5.1, so another solution could be getting the enum values using Enum.GetValues method. 正如@StephenMuecke在其评论中确认的那样, EnumDropDownListFor仅在MVC 5.1中可用,因此另一种解决方案是使用Enum.GetValues方法获取枚举值。 One option to pass that data to your View could be using the ViewBag : 将数据传递到View的一种方法是使用ViewBag

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

Or adding it as a property in your ViewModel in case you were working that way. 或者以这种方式将其添加为ViewModel中的属性。

Later in your View you could use a DropDownList as follows: 稍后,您可以在View中使用DropDownList ,如下所示:

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

According to the solution in this post the following also should work: 根据这篇文章中的解决方案,以下方法也应该起作用:

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

Another solution could be create your own EnumDropDownListFor helper (check this page if you want to read more about this kind of solution): 另一个解决方案是创建您自己的EnumDropDownListFor helper(如果您想了解有关这种解决方案的更多信息,请检查此页面 ):

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

This way you can do the same that I suggested at the beginning of my answer just you need to reference the namespace where you declare your static class with your extension: 这样,您可以执行我在回答开始时建议的相同操作,只是您需要引用使用扩展名声明静态类的名称空间:

@using yourNamespace 
//...

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

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

相关问题 实体框架核心 - 脚手架枚举 - Entity framework Core - Scaffolding enum 如何通过 Entity Framework 6 脚手架创建 model 个类 - How to create model classes through Entity Framework 6 scaffolding Entity Framework Core 应用程序 - 如何在创建和编辑页面中显示从相关 model 填充到当前 model 的下拉列表 - Entity Framework Core app - how to show a DropDown List populated from a related model to the current model in Create & Edit pages 在_layout页面中使用Entity Framework的下拉列表 - Dropdown list using Entity Framework in _layout page 实体框架上下文和 model inheritance 在数据库第一种方法中搭建脚手架时 - Entity Framework context and model inheritance when scaffolding in database first approach 实体框架 - 从视图创建模型? - Entity Framework - Create a model from a view? 实体框架6从现有表创建模型 - Entity Framework 6 Create model from existing table 首先使用代码和DDD在实体框架中模拟枚举列表 - Mimicking an Enum List in Entity Framework using code first and DDD 从数据库实体框架创建一个 JSON 列表 - Create a JSON list from database entity framework 从模型列表创建下拉列表 - create dropdown from Model's List
 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM