Search code examples
asp.net-core-2.1

Adding a null "please select" option to a ASP.NET Core MVC 2.1 select asp-for control


I have an ASP.NET Core (2.1) website, with EF Core hitting SQL Server.

I've generated the controller, and the List, Details, Edit and Delete pages, which use a SelectList in the viewdata to display a list of valid values in the view, but the field is nullable and I need to be able to not force a value into certain dropdown boxes (by default they currently display the first value in the list).

The controller line looks like this (for example):

ViewData["VendorId"] = new SelectList(_context.Vendor, "Id", "Name");

and the view looks like this:

<div class="form-group">
    <label asp-for="VendorId" class="control-label" style="font-weight:bold"></label>
    <select asp-for="VendorId" class="form-control" asp-items="ViewBag.VendorId"></select>
</div>

The default behavior in the form is to show the first item in the list, rather than nothing.

Where/how do I add a null "please select" value to the SelectList? Or do I need to inject it somewhere else, before or after the code above?


Solution

  • Found the answer here: Set Default/Null Value with Select TagHelper

    Changed my view code to:

    <div class="form-group">
        <label asp-for="VendorId" class="control-label" style="font-weight:bold"></label>
        <select asp-for="VendorId" class="form-control" asp-items="ViewBag.VendorId">
            <option selected></option>
        </select>
    </div>
    

    This gives me exactly what I need.