[英]Set Default/Null Value with Select TagHelper
In asp.net mvc you can use:在 asp.net mvc 中,您可以使用:
@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:使用 asp.net 5,如何在 taghelper 中包含默认值或空值(-- SELECT --) :
<select asp-for="Category" asp-items="@ViewBag.Category" class="form-control"></select>
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.上面代码中的disabled
关键字意味着一旦在列表中选择了一个选项,就不能再次选择“--- SELECT ---”行。 If you want the user to be able to blank the selection again (ie if it's bound to a nullable field) then just omit disabled.如果您希望用户能够再次空白选择(即,如果它绑定到一个可为空的字段),那么只需省略禁用。
如果要将值 null 存储到数据库,请使用<option selected value="">Full Access</option>
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 ,如果你为你的模型使用 asp-items ,它使用值 0 为选定的 item ,如果你的标签<option>
与你的默认字符串没有值,
You must use a loop for <option>
and put your default option out of loop.您必须为<option>
使用循环并将默认选项置于循环之外。 This is an example for .Net Core using asp-items:这是 .Net Core 使用 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>
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.可能由于该选项被disabled
它似乎不是一个有效的选择。
btw.: this also works with MVC Core 3 ;-)顺便说一句:这也适用于 MVC Core 3 ;-)
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.