GibboK
GibboK

Reputation: 73938

How to create aDropDown list list from IDictionary<string, string> using Razor in ASp.Net Mvc3

How to create a DropDown list from IDictionary using Razor in ASp.Net Mvc3?? I=m trying the following code wit no success.

 public IDictionary<string, string> CandidatesList = new Dictionary<string, string>();


    Html.DropDownListFor(modal => modal.CandidatesList, new SelectList(Model.CandidatesList, "Value", "Key"))

Upvotes: 0

Views: 122

Answers (1)

Darin Dimitrov
Darin Dimitrov

Reputation: 1038940

Don't bind the dropdown to the same property as the second argument. You must bind it to a primitive type property on your model:

@Html.DropDownListFor(
    model => model.SelectedCandidateKey, 
    new SelectList(Model.CandidatesList, "Value", "Key")
)

where SelectedCandidateKey must be a string property on your view model which will hold the selected item key.

Think of it this way: when you need a dropdownlist in ASP.NET MVC you have to declare 2 properties on your view model:

  1. a primitive type property that will hold the selected value
  2. an IEnumerable<SelectListItem> property that will hold all the available values

Upvotes: 1

Related Questions