How to write a simple Html.DropDownListFor()? How to write a simple Html.DropDownListFor()? asp.net asp.net

How to write a simple Html.DropDownListFor()?


See this MSDN article and an example usage here on Stack Overflow.

Let's say that you have the following Linq/POCO class:

public class Color{    public int ColorId { get; set; }    public string Name { get; set; }}

And let's say that you have the following model:

public class PageModel {   public int MyColorId { get; set; }}

And, finally, let's say that you have the following list of colors. They could come from a Linq query, from a static list, etc.:

public static IEnumerable<Color> Colors = new List<Color> {     new Color {        ColorId = 1,        Name = "Red"    },    new Color {        ColorId = 2,        Name = "Blue"    }};

In your view, you can create a drop down list like so:

<%= Html.DropDownListFor(n => n.MyColorId,                          new SelectList(Colors, "ColorId", "Name")) %>


<%:      Html.DropDownListFor(           model => model.Color,            new SelectList(                  new List<Object>{                        new { value = 0 , text = "Red"  },                       new { value = 1 , text = "Blue" },                       new { value = 2 , text = "Green"}                    },                  "value",                  "text",                   Model.Color           )        )%>

or you can write no classes, put something like this directly to the view.


Avoid of lot of fat fingering by starting with a Dictionary in the Model

namespace EzPL8.Models{    public class MyEggs    {        public Dictionary<int, string> Egg { get; set; }        public MyEggs()        {            Egg = new Dictionary<int, string>()            {                { 0, "No Preference"},                { 1, "I hate eggs"},                { 2, "Over Easy"},                { 3, "Sunny Side Up"},                { 4, "Scrambled"},                { 5, "Hard Boiled"},                { 6, "Eggs Benedict"}            };    }    }

In the View convert it to a list for display

@Html.DropDownListFor(m => m.Egg.Keys,                         new SelectList(                             Model.Egg,                              "Key",                              "Value"))