asp.net-mvc 如何将 MVC Html Helper .DropDownListFor<> 与 Enum 一起使用

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/6146204/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me): StackOverFlow

提示:将鼠标放在中文语句上可以显示对应的英文。显示中英文
时间:2020-09-08 01:13:13  来源:igfitidea点击:

How to use MVC Html Helper .DropDownListFor<> with an Enum

asp.net-mvcasp.net-mvc-3razorhtml-helperhtml.dropdownlistfor

提问by Jed

In my MVC 3 Razor app, I have a Model with an enum..

在我的 MVC 3 Razor 应用程序中,我有一个带有枚举的模型..

Model Example:

模型示例:

public class EmployeeModel
{
 public enum Title
 {
  Accountant = 111,
  Sales = 222,
  Production = 333 
 }

 [Required]
 public string Name {get; set;}

 [Required]
 public Title JobTitle {get; set;}
}

In my View I would like to use the Html helpers to build an Html Form...

在我的视图中,我想使用 Html 助手来构建一个 Html 表单......

View Example:

查看示例:

@model ..Models.EmployeeModel

@using (Html.BeginForm())
{
 @Html.LabelFor(m => m.Name)
 @Html.TextBoxFor(m => m.Name)
 <br>

 @Html.LabelFor(m => m.JobTitle)
 @Html.DropDownListFor(m => m.JobTitle, ??How do I get Title enum values??)
 <br>

 <input type="submit />
}

The output of the DropDownListFor that I trying to achieve would look like this: Note the option values match the initialized values of the enum

我试图实现的 DropDownListFor 的输出如下所示: 注意选项值与枚举的初始化值匹配

<select name="JobTitle">
 <option value="-1">Choose a Job Title</option>
 <option value="111">Accountant</option>
 <option value="222">Sales</option>
 <option value="333">Production</option>
</select>

How do I get the DropDownListFor<> helper to create a select/option element based on the Title enum of the Model?

如何让 DropDownListFor<> 助手根据模型的 Title 枚举创建选择/选项元素?

Also, is it possible to have the DropDownListFor<> helper to add an extra (that is not part of the enum) similar to the "Choose a Job Title" option in the example above?

另外,是否可以让 DropDownListFor<> 助手添加一个类似于上面示例中的“选择职位”选项的额外(不是枚举的一部分)?

采纳答案by Tomas Aschan

You could possibly get a String[]with the names of the enum values and create a dropdown from that. In your view model, add a property Titlesof type SelectListItemand add the enum values and names to that. You can get the names and values through the System.Enumtype.

您可能会获得String[]带有枚举值名称的 a 并从中创建一个下拉列表。在您的视图模型中,添加一个Titlestype属性SelectListItem并为其添加枚举值和名称。您可以通过System.Enum类型获取名称和值。

var defaultItem = new SelectListItem();
defaultItem.Value = -1;
defaultItem.Text = "Choose a title";
defaultItem.Selected = true;
model.TitleSelectItems.add(defaultItem);

String[] names = System.Enum.GetNames(typeof(Title));
Int[] values = System.Enum.GetValues(typeof(Title));

for (int i = 0; i<names.Length; i++)
{
    var item = new SelectListItem();
    item.Text = names[i];
    item.Value = values[i];
    model.TitleSelectItems.Add(item);
}

It's kind of ugly, but it'll work.

这有点难看,但它会起作用。

回答by Jed

I just stumbled on this StackO question/answer- not only is my question here an exact duplicate, but the answer given by Mike McLaughlinis the best solution I've seen for using DropdownListFor<>with Enums. Specifically, Mike points us to a solution that he found by Morgan Leroi

我只是偶然在这个StackO提问/回答-不仅是我的问题在这里的精确副本,但麦克·麦克劳克林给出的答案是我见过使用的最佳解决方案DropdownListFor<>Enums。具体来说,Mike 向我们指出了他由 Morgan Leroi 找到的解决方案

Morgan's quick solution is:

摩根的快速解决方案是:

@Html.DropDownListFor(model => model.State, new SelectList(Enum.GetValues(typeof(MyNamespace.Enums.States))))

But, Morgan has made an Extension that makes the implementation of the DropDownListFor<>with enums even more compact. You can download Morgan's Visual Studio Solution here.

但是,Morgan 做了一个扩展,使得DropDownListFor<>with 枚举的实现更加紧凑。您可以在此处下载 Morgan 的 Visual Studio 解决方案。

That said, I think we should close this question as it's an exact duplicate.

也就是说,我认为我们应该关闭这个问题,因为它完全重复。

回答by Ramya

Here is the solution

这是解决方案

public enum Months
{
January=1,
February=2,
March=3,
April =4,
May=5,
June=6
}

public ActionResult Index()
{

ViewBag.Months = (from Months m in Enum.GetValues(typeof(Months))
                select new SelectListItem { Text = m.ToString(), Value = Convert.ToUInt16(m).ToString() });

return View();  
}

Add ViewBag name in DropDownList :

在 DropDownList 中添加 ViewBag 名称:

<%=Html.DropDownList("Months") %>

回答by Emran Hussain

An encapsulated HTML Helper Extension is available here :

封装的 HTML Helper Extension 可在此处获得:

http://www.spicelogic.com/Journal/ASP-NET-MVC-DropDownListFor-Html-Helper-Enum-5

http://www.spicelogic.com/Journal/ASP-NET-MVC-DropDownListFor-Html-Helper-Enum-5

the source code snapshot:

源代码快照:

enter image description here

在此处输入图片说明

You can download the full source code of the project from the link.

您可以从链接下载该项目的完整源代码。

回答by Jed

Here's a way using Html Helpers:

这是使用 Html Helpers 的一种方法:

Model

模型

public class Person
{
    public string Name { get; set; }
    public JobTitle Job { get; set; }
    public enum JobTitle
    {
        Accountant = 111,
        Sales = 222,
        Production = 333
    }
}

View

看法

@model MvcApplication1.Models.Person

@{
    ViewBag.Title = "Index";
}

@using (Html.BeginForm())
{
    @Html.TextBoxFor(n => n.Name)
    @Html.DropDownListFor(c => c.Job, new[]{
        new SelectListItem() {Text = MvcApplication1.Models.Person.JobTitle.Accountant.ToString(), 
            Value=((int)MvcApplication1.Models.Person.JobTitle.Accountant).ToString()}
        ,new SelectListItem() {Text = MvcApplication1.Models.Person.JobTitle.Production.ToString(), 
            Value=((int)MvcApplication1.Models.Person.JobTitle.Production).ToString()}
        ,new SelectListItem() {Text = MvcApplication1.Models.Person.JobTitle.Sales.ToString(),
            Value=((int)MvcApplication1.Models.Person.JobTitle.Sales).ToString()}}
            , "Choose a Job Title")                               
}

HTML Output

HTML 输出

<!DOCTYPE html>
<html>
<head>
    <title>Index</title>
</head>
<body>
<form action="/" method="post">
<input id="Name" name="Name" type="text" value="" />
<select id="Job" name="Job">
<option value="">Choose a Job Title</option>
<option value="111">Accountant</option>
<option value="333">Production</option>
<option value="222">Sales</option>
</select>
</form>
</body>
</html>

回答by r03

I solved it with this extension:

我用这个扩展解决了它:

public static SelectList ToSelectListWithDefault<TEnum>(this TEnum enumObj, string defValue, string defText) where TEnum : IConvertible
{
    var values = new List<SelectListItem>();
    var defItem = new SelectListItem() { Value = defValue, Text = defText };
    values.Add(defItem);
    foreach (TEnum e in Enum.GetValues(typeof(TEnum)))
    {
        values.Add(new SelectListItem() { Value = e.ToInt16(null).ToString(), Text = e.ToString() });
    }

    return new SelectList(values, "Value", "Text", defItem);
}   

(I found the extension on SO, but without the default value)

(我在 SO 上找到了扩展名,但没有默认值)