4

Possible Duplicate:
How do you create a dropdownlist from an enum in ASP.NET MVC?

I know there are several post that deal with dropdown in MVC3. I havent been able to find one that deal with my specific problem.

I am trying to get all the options of my Enum into a dropdown in the View.

Here is my Enum/Class:

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

My view looks like this:

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

My controller would have the action result to give and receive data:

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

I am not worried about the Post(hence the lack of effort in reproducing the create code on receiving data from View), just the Get. Also the correct code for in the View from the dropdown.

I have been advised not to use ViewBag. Other than that I am open to any good suggestions.

Community
  • 1
  • 1
dan_vitch
  • 4,477
  • 12
  • 46
  • 69

1 Answers1

7

I use the following code for enum drop down boxes:

@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]")
Ghlouw
  • 1,440
  • 16
  • 19
  • Did you had a problem in Edit action? meaning in edit action the current value is not selected in the dropdown – Silagy Mar 24 '15 at 14:58