Html.DropDownList default selected item

2020-04-05 08:21发布

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条回答
太酷不给撩
2楼-- · 2020-04-05 08:56

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)
)
查看更多
登录 后发表回答