Html.DropDownList default selected item

2020-04-05 08:18发布

问题:

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 ?

回答1:

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)
)