0

I have a dropdownlist for

@Html.DropDownListFor(model => f.MovieID, (SelectList)ViewBag.MoviesList, "--Select One--", htmlAttributes: new { @class = "form-control" })

In the controller I set the ViewBag.MovesList to a SelectList. It is a valid Select List. I'm trying to reuse the same select list for multiple items in a foreach loop. However, when it is rendered the existing MovieID value is not being selected in the drop down list. I have seen many similar questions but none of their root causes I am seeing in mine. Also, based on other questions simimar, this is slightly different then others because it is inside of a loop.

dko
  • 698
  • 1
  • 6
  • 18
  • 1
    shouldn't that be model => model.MovieID or f => f.MovieID? – Simon May 08 '17 at 17:42
  • 1
    Possible duplicate of [MVC5 Razor html.dropdownlistfor set selected when value is in array](http://stackoverflow.com/questions/37407811/mvc5-razor-html-dropdownlistfor-set-selected-when-value-is-in-array) –  May 08 '17 at 22:59

1 Answers1

1

Try something like below:

@Html.DropDownListFor(model => model.MovieID, new SelectList((IEnumerable)ViewBag.MoviesList, "Value", "Text", Model.MovieID), new { @class = "form-control" })

Where Value is what you want to pass to the action invoked and Text is what you want to show in the dropdown.

Adnan Niloy
  • 469
  • 11
  • 18
  • I'm going to tweak this answer slightly but I believe this should do it. Just sad I need to create a new SelectList everytime. I can't just set a property on it and change the selected value for each drop down list in a loop – dko May 10 '17 at 06:59