Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Html.DropDownList default selected item

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 ?

like image 430
kbaccouche Avatar asked Jun 06 '13 08:06

kbaccouche


People also ask

How do I show default selected value in dropdown?

The option tag contains the value that would be used when selected. The default value of the select element can be set by using the 'selected' attribute on the required option. This is a boolean attribute. The option that is having the 'selected' attribute will be displayed by default on the dropdown list.

How do I preselect a select option?

A select box also called drop down box provides an option to list down various options in the form of drop down list. You can also preselect a value in dropdown list of items in HTML forms. For that, add selected in the <option> tag for the value you want to preselect.

How do I set default value in ng options?

Use ng-init to set default value for ng-options .


1 Answers

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)
)
like image 189
Darin Dimitrov Avatar answered Nov 02 '22 15:11

Darin Dimitrov