如何使用 MVC Html Helper .DropDownListFor<>带有枚举

发布于 2024-11-10 03:44:22 字数 1162 浏览 0 评论 0 原文

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

模型示例:

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 表单...

视图示例:

@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 的输出实现看起来像这样: 请注意,选项值与枚举的初始化值相匹配

<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<>帮助器根据模型的标题枚举创建选择/选项元素?

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

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

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

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

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

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?

如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。

扫码二维码加入Web技术交流群

发布评论

需要 登录 才能够评论, 你可以免费 注册 一个本站的账号。

评论(6

牛↙奶布丁 2024-11-17 03:44:22

您可能会获得一个带有枚举值名称的 String[] 并从中创建一个下拉列表。在视图模型中,添加 SelectListItem 类型的属性 Titles 并向其中添加枚举值和名称。您可以通过 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);
}

这有点丑陋,但它会起作用。

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.

天荒地未老 2024-11-17 03:44:22

我刚刚偶然发现了这个 StackO 问题/答案 - 我的问题不仅是完全重复的,但 Mike McLaughlin 给出的答案是我见过的使用 DropdownListFor<> 的最佳解决方案Enums。具体来说,Mike 向我们指出他由 Morgan Leroi 找到的解决方案< /a>

Morgan 的快速解决方案是:

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

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

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

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

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

倾城泪 2024-11-17 03:44:22

这是解决方案

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

在 DropDownList 中添加 ViewBag 名称:

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

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 :

<%=Html.DropDownList("Months") %>
昔梦 2024-11-17 03:44:22

这是使用 Html Helpers 的方法:

模型

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

视图

@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 输出

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

Here's a way using 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

<!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>
复古式 2024-11-17 03:44:22

封装的 HTML 帮助器扩展可在此处获取:

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

源代码快照:

在此处输入图像描述

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

An encapsulated HTML Helper Extension is available here :

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.

眼泪淡了忧伤 2024-11-17 03:44:22

我用这个扩展解决了它:(

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

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

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)

~没有更多了~
我们使用 Cookies 和其他技术来定制您的体验包括您的登录状态等。通过阅读我们的 隐私政策 了解更多相关信息。 单击 接受 或继续使用网站,即表示您同意使用 Cookies 和您的相关数据。
原文