1

In my view, all fields are binding to the model, except the dropdowns. The list gets populated, but the selected value is not set.

In my controller, I set the data source like this:

ViewBag.LocationID = new SelectList(db.Locations, "ID", "Name", model.LocationID);

In my view, I setup the dropdown like this:

@Html.DropDownListFor(model => model.LocationID, (SelectList)ViewBag.LocationID, string.Empty, htmlAttributes: new { @class = "form-control" })

In the questions that I read that had similar issues, the problem was that they weren't setting the selected value at the time of creating the SelectList, but I am doing that.

What's preventing the selected value from being bound by the model?

Ali Almohsen
  • 1,311
  • 3
  • 13
  • 24
  • 1
    Note also that the 4th parameter of the `SelectList` constructor is pointless (its ignored except in the case where you do not bind to anything e.g. `@Html.DropDownList("NotAProperty", .....)`) –  Dec 14 '17 at 10:02
  • @StephenMuecke Wow, resolved that. So in short, my issue was that the ViewBag name should be different than the property's name. Frustrating to have spent so much time on that for this to be the issue. Thanks a lot (once again) for your help! – Ali Almohsen Dec 14 '17 at 10:26
  • Your editing data so ALWAYS use a view model, and that view model will contain a property (say) `IEnumerable LocationList`, and then its simply `@Html.DropDownListFor(m => m.SelectedLocation, Model.LocationList, ....)` –  Dec 14 '17 at 10:29
  • @StephenMuecke Oh, that sounds like an even smarter idea. Just got what you meant. I took my solution from the DotNetFiddle you posted, even though I didn't like the idea of using the ViewBag to populate the dropdown values to begin with. – Ali Almohsen Dec 14 '17 at 10:33

0 Answers0