MVC5 Razor html.dropdownlistfor set selected when value is in array

Unfortunately @Html.DropDownListFor() behaves a little differently than other helpers when rendering controls in a loop. This has been previously reported as an issue on CodePlex (not sure if its a bug or just a limitation)

The are 2 option to solve this to ensure the correct option is selected based on the model property

Option 1 (using an EditorTemplate)

Create a custom EditorTemplate for the type in the collection. Create a partial in /Views/Shared/EditorTemplates/AggregationLevelConfiguration.cshtml (note the name must match the name of the type

@model yourAssembly.AggregationLevelConfiguration
@Html.DropDownListFor(m => m.HelperCodeType, (SelectList)ViewData["CodeTypeItems"])
.... // other properties of AggregationLevelConfiguration

and then in the main view, pass the SelectList to the EditorTemplate as additionalViewData

@using (Html.BeginForm())
{
  ...
  @Html.EditorFor(m => m.Configurations , new { CodeTypeItems = Model.CodeTypeItems })
  ...

Option 2 (generate a new SelectList in each iteration and set the selectedValue)

In this option your property CodeTypeItems should to be IEnumerable<GenericIdNameType>, not a SelectList (or just make codeTypes a public property). Then in the main view

@Html.DropDownListFor(m => m.Configurations[0].HelperCodeType, new SelectList(Model.CodeTypeItems, "Id", "Name", Model.Configurations[0].HelperCodeType)

Side note: there is no need to use new { id = "Configurations[0].HelperCodeType" – the DropDownListFor() method already generated that id attribute

Leave a Comment