0

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"))
GibboK
  • 71,848
  • 143
  • 435
  • 658

1 Answers1

1

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
Darin Dimitrov
  • 1,023,142
  • 271
  • 3,287
  • 2,928
  • May I ask yo why DropDownListFor is not available on IDictionary? thanks – GibboK Oct 08 '12 at 08:25
  • What do you mean by not available? Are you asking why you cannot bind a DropDownListFor to a complex type as first argument? That's because it wouldn't make sense. In HTML only the selected value is sent to the server when you submit a form containing a ` – Darin Dimitrov Oct 08 '12 at 08:26
  • Thanks Darin for clarification :-) – GibboK Oct 08 '12 at 08:34
  • this answer help me to understand you point http://stackoverflow.com/questions/4674033/mvc-3-layout-page-razor-template-and-dropdownlist – GibboK Oct 08 '12 at 08:51