Html.DropDownList default selected item

kbaccouche picture kbaccouche · Jun 6, 2013 · Viewed 23.1k times · Source

I am displaying a list of dropDownLists inside a ForEach loop.

This is the code

@foreach (var task in Model.TaskList)
    {
        <tr>
            <td>@Html.DropDownList("ModuleID", new SelectList(Model.ModuleList, "ModuleID", "Ordre"))
            </td>
        </tr>
    }

I want the Module of each Task to be selected by default. This could easily be done using DropDownList if only I was binding the dropDownList to a view model, but that's not the case.

Any ideas ?

Answer

Darin Dimitrov picture Darin Dimitrov · Jun 6, 2013

This could easily be done using DropDownList if only I was binding the dropDownList to a view model

You already know the correct answer and are still asking the question. And are still not using a view model.

What else can I say, you could pass the value of the element that you want preselected as 4th argument of the SelectList constructor:

@Html.DropDownList(
    "ModuleID", 
    new SelectList(Model.ModuleList, "ModuleID", "Ordre", task.ModuleID)
)