How to set default value to select list in MVC during run time

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)

Create a custom EditorTemplate for the type in the collection.

In /Views/Shared/EditorTemplates/provider_service_dtls.cshtml (note the name must match the name of the type)

@model yourAssembly.provider_service_dtls

@Html.HiddenFor(m => m.service_id)
@Html.DropDownListFor(m => m.activity_code_type, (SelectList)ViewData["options"], "--- Select Activity Code Type ---")
.... // html helpers for other properties of provider_service_dtls

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

@model yourAssembly.provider_preapproval 

@using (Html.BeginForm())
{
  .... // html helpers for other properties of provider_preapproval

  @Html.EditorFor(m => m.provider_service_dtls, new { options = (SelectList)@ViewBag.activity_code_type })
  ...

The EditorFor() methods accepts IEnumerable<T> and will generate the controls for each item in the collection

Edit

An alternative is to create a new SelectList in each iteration of the for loop, where you need to set the Selected property of SelectList. This means that your ViewBag property must be IEnumerable<T>, not a SelectList, for example in the controller

ViewBag.ActivityCodeTypeList = new[]
{
  new { ID = 1, Name = "Internal" },
  new { ID = 2, Name = "Standard" }
}

and in the view

for (int i = 0; i < Model.provider_service_dtls.Count; i++)
{
  @Html.DropDownListFor(m => m => m.provider_service_dtls[i].activity_code_type,
    new SelectList(ViewBag.ActivityCodeTypeList, "ID", "Name", Model.provider_service_dtls[i].activity_code_type),
    "--- Select Activity Code Type ---")
}

Leave a Comment