[英]How to make @Html.DropDownList() allow null
我使用 Visual Studio 从数据库自动生成控制器和视图。 在数据库中,有一个表 dbo.Items,它有一个FOREIGN KEY (CategoryID) REFERENCES Categories(Id)
为 Items/Create 生成的 View 有这个块,它强制用户在添加新 Item 时从下拉列表中选择 01 类别,不允许空值:
<div class="form-group">
@Html.LabelFor(model => model.CategoryID, "CategoryID", htmlAttributes: new { @class = "control-label col-md-2" })
<div class="col-md-10">
@Html.DropDownList("CategoryID", null, htmlAttributes: new { @class = "form-control" })
@Html.ValidationMessageFor(model => model.CategoryID, "", new { @class = "text-danger" })
</div>
</div>
如何使 Null 选项可用?
Html.DropDownList()
是一个 html 辅助方法,它将生成用于呈现 SELECT 元素的 HTML 标记。 它本身不做任何“允许/不允许”的事情。
当您根据视图模型属性和在其上定义的数据注释提交表单时,MVC 模型验证框架会在服务器端进行模型验证。 helper 方法还生成所需的数据属性,jQuery 验证插件可以使用这些属性进行客户端验证。
要允许在 SELECT 元素中不选择任何选项,请将CategoryID
属性更改为可为空的 int。 如果你有一个视图模型,你可以在那里更新。
public class YourViewmodel
{
public int? CategoryID { set;get;}
}
您还需要更新数据库架构以在CategoryId
列中保存可为空的值。 如果您使用数据库优先方法,您可以更改数据库架构(将列更改为可为空),然后重新生成实体类。
我还建议您使用DropDownListFor
助手
@Html.DropDownListFor(x=>x.CategoryID,ViewBag.CountryCode as List<SelectListItem>,
"select one", new { @class = "form-control" })
假设ViewBag.CountryCode
是您在 GET 操作方法中设置的SelectListItem
列表。
您可以使用休闲重载版本最初显示“选择选项”...
@Html.DropDownList("CategoryID", null, "select option", new { @class = "form-control" })
并且每当您向 CategoryID 下拉列表添加选项时,您都需要将“选择选项”添加为第一个,然后再添加......
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.