Click here to Skip to main content
15,888,286 members
Please Sign up or sign in to vote.
0.00/5 (No votes)
See more:
This one has got me scratching my head as I'm still pretty new to MVC and Razor. I'm building a couple of Select Item lists dynamically that have one item pre-selected, no biggie. What is getting me is that after the list is passed into the Html helper function, the selected item is being de-selected and the list defaults to the first item. Stepping through the page load, the List<SelectListItem> has the correct values prior to entering the helper function. I'm NOT using the Entity Framework for database operations.

<td>
  @{
    List<SelectListItem> itemList = Functions.GetListForProperty(property);
  }
  <% Correct value is selected in the list %>
  @Html.DropDownList("PropertyList", itemList)
  <% Selected = false for the previously selected item, wtf? %>
</td>


Is there some setting I'm missing here. The view is built with the scaffolding but I have other views with dynamically generated drop down lists that don't behave this way.

What I have tried:

I've tried both flavors of the helper function, @Html.DropDownListFor(Model => model.property, IEnumerable<SelectListItem>) and @Html.DropDownList("Name", IEnumerable<SelectListItem>) and get the same results. I have even inlined the code that builds the list and still get the same thing.
Posted
Updated 18-Feb-16 8:11am

1 solution

Figured out my problems. Turns out is was something very simple. The problem was with the view bag.

Problem with @Html.DropDownListFor(Model => Model.Property, selectList) is that the Model.Property was not of the type List<SelectListItem> so it wouldn't be bound when the ViewBag rendered the view in the response.

Problem with @Html.DropDownList("PropertyName", selectList) is that I was assigning it the same name as the property it was fetching data for. Once I changed the Name string to something like "PropertyNameSelect," the selected values rendered correctly to the http response string.
 
Share this answer
 

This content, along with any associated source code and files, is licensed under The Code Project Open License (CPOL)



CodeProject, 20 Bay Street, 11th Floor Toronto, Ontario, Canada M5J 2N8 +1 (416) 849-8900