2011-03-13 44 views
4

可能重複:
How do you create a dropdownlist from an enum in ASP.NET MVC?枚舉來查看下拉MVC3

我知道有幾個職位,在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); 
    } 

我並不擔心這個帖子(因此在從View接收數據時再現創建代碼時缺乏努力),只是第e獲取。從下拉菜單中查看正確的代碼。

我被建議不要使用ViewBag。除此之外,我接受任何好的建議。

回答

7

我用枚舉下面的代碼下拉框:

@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]") 
+0

做了你在編輯操作的問題嗎?在編輯操作中,在下拉菜單中未選擇當前值 – Silagy 2015-03-24 14:58:28