Set Default/Null Value with Select TagHelper

馋奶兔 提交于 2020-01-12 02:55:09

问题


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>

回答1:


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.




回答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>



回答3:


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




回答4:


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 ;-)



来源:https://stackoverflow.com/questions/34845786/set-default-null-value-with-select-taghelper

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!