Roro
Roro

Reputation: 117

Dropdown lists first option to be null

I Have a dropdownlist that allows you to selcect an exsiting Driver ID. when the page loads the first Driver ID is already selected and I would rather allow the Driver ID dropdownlist to first have a null value selected when the page loads. How will I do this? This is my Driver ID view:

 <div class="form-group">
                @Html.LabelFor(model => model.DriverID, "Driver Cell", new { @class = "control-label col-md-2" })
                <div class="col-md-10">
                    @Html.DropDownList("DriverID", null, htmlAttributes: new { @class = "box" })
                    @Html.ValidationMessageFor(model => model.DriverID)
                </div>
            </div>

Upvotes: 0

Views: 69

Answers (2)

Larry
Larry

Reputation: 688

You can also use the asp-for tag helper with a SelectListItem list

Then this is what you write in your form in the view

<select asp-for="(Whatever the value is associated to)" asp-items="The List<SelectListItem> list">
    <option disabled selected>---Select---</option> 
<!-- This line will go to the top of the dropdown list -->
</select>

This will create a dropdown list where by default nothing is selected and this default value will be null

You can also refer to this other post on stack overflow:

Set Default/Null Value with Select TagHelper

Upvotes: 0

Dandy
Dandy

Reputation: 2177

You can use

@Html.DropDownList("DriverID", null, "Select a driver", htmlAttributes: new { @class = "box" })

but this dropdown will be empty since you are passing null as SelectList.

Upvotes: 1

Related Questions