Invalid MVC Dropdown

I'm sure I'm missing something obvious, but it drives me crazy! If I specify the html options, the value of my dropdown will not be set.

In my controller, I retrieve the parameters for my drop-down list:

  ViewData ["Coordinator"] = new SelectList (userRepository.GetIdUserList (1), 
                           "ID", "Signature", edCenter.Coordinator); 

In my opinion, I am filling out a drop down list:

  Html.DropDownList ("Coordinator", (IEnumerable) ViewData ["Coordinator"],
                    new {style = "width: 175px"}) 

The dropdown values โ€‹โ€‹fill out fine, but no list value is selected.

However, if I just use:

  Html.DropDownList ("Coordinator"); 

Everything works perfectly.

What is going wrong?

+4
source share
2 answers

I ran into a similar problem yesterday, so if you are still getting the same result, there is one more thing to consider. DropDownList sometimes ignores the selected value of your SelectList, which is annoying, but what it does is try to get the selected value from ModelState, ViewData and Model using the field name as the key. In your case, you save the list in ViewData ["Coordinator"], the key has the same name as DropDown. Try the following:

ViewData["CoordinatorList"] = new SelectList(userRepository.GetIdUserList(1), "ID", "Signature",edCenter.Coordinator); ViewData["Coordinator"] = dCenter.Coordinator; 

Then in the view:

  <%=Html.DropDownList("Coordinator",((SelectList)ViewData["CoordinatorList"]).AsEnumerable(), new {style="width:175px"}) %> 

If you want to see what happens behind the curtains, open the reflector (or get the MVC source) and look at this method: System.Web.Mvc.Html.SelectExtensions.SelectInternal ()

+4
source

the second parameter DropDown Helper accepts an object of type IEnumerable (Of SelectListItem), but you passed an object of type IEnumerable (Of SelectList) so here is how to write the code:

  <%=Html.DropDownList("Coordinator",((SelectList)ViewData["Coordinator"]).AsEnumerable(), new {style="width:175px"}) %> 
+1
source

All Articles