Alex Rivera | Logout

How to add static list of items in MVC Html.DropDownList()

Asked 2009-05-15T05:41:03.893
14

I would like to assign a static list of items in a SelectList() to a Html.DropDownList() in ASP.NET MVC, what is the best practice?

I was about to try to find a way to use new SelectList(new {key = "value"}... but one, that didn't work, and two, would I be breaking a law here, should my static list be declared in ViewData anyway and passed as IList/IENumerable?

Edit
Report

1 Answer

3

OK I decided to take my own advice, and this should be defined in the controller:

FYI, I just returned:

PageData data = new PageData()
           {
               Formats = new[]
                             {
                                 new { ID = "string", Name = "Text" },
                                 new { ID = "int", Name = "Numeric" },
                                 new { ID = "decimal", Name = "Decimal" },
                                 new { ID = "datetime", Name = "Date/Time" },
                                 new { ID = "timespan", Name = "Stopwatch" }
                             },
               .............

           };
return View(data);

... (ignore context) and in the View ASPX side:

<%= Html.DropDownList("type.field", new SelectList(ViewData.Model.Formats, "ID", "Name"...

If anyone has a more optimal way of doing this I'll be happy to accept their answer.

answered 2009-05-15T06:05:31.417

Your Answer