Enum to view DropDown MVC3

Possible duplicate:
How to create a dropdown from an enumeration in ASP.NET MVC?

I know that there are several posts that relate to the dropdown in MVC3. I could not find one that relates to my specific problem.

I am trying to get all variants of my Enum from the 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 is as follows:

 @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 will receive the result of the action for receiving and receiving 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'm not worried about Post (hence the lack of effort to reproduce the creation code when retrieving data from View), just Get. Also the correct code to present in the drop-down list.

I am not recommended to use ViewBag. In addition, I am open to any good suggestions.

+4
source share
1 answer

I use the following code for dropdown enumeration 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]") 
+7
source

Source: https://habr.com/ru/post/1343512/


All Articles