Set Default/Null Value with Select TagHelper
Asked Answered
C

4

48

In asp.net mvc you can use:

@Html.DropDownListFor(model => model.Category, ViewBag.Category as IEnumerable<SelectListItem>, "-- SELECT --", new { @class = "form-control" })

Using asp.net 5, how do I include the default or null value (-- SELECT --) in a taghelper:

<select asp-for="Category" asp-items="@ViewBag.Category"  class="form-control"></select>
Chase answered 18/1, 2016 at 1:4 Comment(0)
S
99

You can just insert an option item inside the select:

<select asp-for="Category" asp-items="@ViewBag.Category"  class="form-control">
    <option disabled selected>--- SELECT ---</option>
</select>

The disabled keyword in the code above means that the "--- SELECT ---" row cannot be picked again once a choice has been selected in the list. If you want the user to be able to blank the selection again (i.e. if it's bound to a nullable field) then just omit disabled.

Sivia answered 18/1, 2016 at 1:41 Comment(3)
I needed to set the option's value to an empty string to allow the user to null out the underlying nullable int field: <option value="">None</option>Magdaleno
And if you don't want disabled option to show in the drop-down list, you can style it to display none.Wageworker
For nullable columns the default option should have value="" otherwise the model won't bindDustindustman
M
8

If you want to store value null to database then use <option selected value="">Full Access</option>

Motorman answered 9/12, 2018 at 17:11 Comment(2)
what if I need it to be null? if default option is submitted, I want it to be null instead of empty string.Eternalize
This is the 2nd half of the answer (if you need to support nullable navigation properties, and not only have a header on the Select indicating "Please select a value")Comet
N
2

If you use asp-items for your model , It uses value 0 for selected item , If you have tag <option> with your default string without value ,

You must use a loop for <option> and put your default option out of loop. This is an example for .Net Core using asp-items:

<select asp-for="DepartmentUnit" asp-items="@Model.DepartmentUnits" class="form-control"></select>

and Now this is another example for using loop:

<select>
<option val="">--Select--</option>
foreach(item in Model.DepartmentUnits)
{<option val="@item.val">@item.title</option>}
</select>
Nam answered 6/3, 2018 at 10:24 Comment(0)
C
1

This answer by Matt:

    <select asp-for="Category" asp-items="@ViewBag.Category"  class="form-control">
        <option disabled selected>--- SELECT ---</option>
    </select>

also works with validation. Probably due to the option being disabled it seems not to be a valid selection.

btw.: this also works with MVC Core 3 ;-)

Cadenza answered 28/10, 2019 at 11:8 Comment(0)

© 2022 - 2024 — McMap. All rights reserved.