【问题标题】:Enum to View DropDown MVC3 [duplicate]枚举查看下拉 MVC3 [重复]
【发布时间】:2011-07-14 08:42:38
【问题描述】:

可能重复:
How do you create a dropdownlist from an enum in ASP.NET MVC?

我知道有几篇文章处理 MVC3 中的下拉菜单。我还没有找到一个可以解决我的具体问题的。

我正在尝试将我的 Enum 的所有选项放入视图中的下拉列表中。

这是我的枚举/类:

namespace ColoringBook 
public enum Colors
{
    Red = 0,
    Blue = 1,
    Green = 2,
    Yellow = 3
}

public class Drawing
{
    private Colors myColor;

    public Colors MyColor
    {
        get { return this.myColor; }
        set { this.myColor= value; }
    }

    public Drawing(Colors color)
    {
        this.myColor = color;
    }
}

我的观点是这样的:

@model ColoringBook.Drawing


@{
Title = "Create";
}

<h2>Create</h2>

@using (Html.BeginForm()) 
{
@Html.ValidationSummary(true)
<fieldset>
    <legend>Color</legend>


    <div class="editor-label">
        @Html.LabelFor(model => model.Color)
    </div>
    <div class="editor-field">
        //not sure how to fill
        //@Html.DropDownList("Color",new SelectList())

    </div>
 <p>
        <input type="submit" value="Create" />
 </p>
</fieldset>
}

我的控制器会有动作结果来提供和接收数据:

public class ColorController: Controller
{
     public ActionResult Create()
     {
        return View();
     }

     [HttpPost]
     public ActionResult Create(Colors dropdownColor)
     {
        //do some work and redirect to another View
        return View(dropdownColor); 
     }

我不担心 Post(因此在从 View 接收数据时复制创建代码时缺乏努力),只担心 Get。下拉列表中的视图中的正确代码也是如此。

有人建议我不要使用 ViewBag。除此之外,我愿意接受任何好的建议。

【问题讨论】:

    标签: asp.net-mvc-3


    【解决方案1】:

    我对枚举下拉框使用以下代码:

    @Html.DropDownListFor(model => model.Color, Enum.GetValues(typeof(ColoringBook.Colors)).Cast<ColoringBook.Colors>().Select(v => new SelectListItem
                   {
                       Text = v.ToString().Replace("_", " "),
                       Value = ((int)v).ToString()
                   }), "[Select]")
    

    【讨论】:

    • 您在编辑操作中遇到问题了吗?在编辑操作中表示当前值未在下拉列表中选择
    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 2013-10-03
    • 1970-01-01
    • 1970-01-01
    • 2014-07-17
    • 2018-10-10
    • 2012-08-31
    • 2016-03-05
    相关资源
    最近更新 更多