如何使用MVC的HTML帮助.DropDownListFor<>有一个枚举 [英] How to use MVC Html Helper .DropDownListFor<> with an Enum

查看:92
本文介绍了如何使用MVC的HTML帮助.DropDownListFor<>有一个枚举的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

在我的MVC 3剃须刀的应用程序,我有一个枚举模型..

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

型号示例:

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

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

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

在我看来,我想使用HTML佣工建立一个HTML表单...

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

查看示例:

@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 />
}

这是我想实现应该是这样的DropDownListFor的输出:
注意选项值匹配枚举的初始化值

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

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

我如何获得DropDownListFor&LT;?>帮助创建基于模型的标题枚举选择/选项元素

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

此外,是否有可能有DropDownListFor&LT;>助手来添加一个额外的(即不枚举的一部分)类似于上面的例子中,选择一个职位的选项。

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?

推荐答案

你可能得到一个的String [] 通过枚举值的名称,并创建一个下拉列表那。在您的视图模型,添加属性标题类型 SelectListItem 和枚举值和名称补充。你可以通过 System.Enum 键入名称和值。

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 Titles of type SelectListItem and add the enum values and names to that. You can get the names and values through the System.Enum type.

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.

这篇关于如何使用MVC的HTML帮助.DropDownListFor&LT;&GT;有一个枚举的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆