【问题标题】:How to make @Html.DropDownList() allow null如何使@Html.DropDownList() 允许为空
【发布时间】:2018-12-01 17:43:40
【问题描述】:

我使用 Visual Studio 从数据库中自动生成控制器和视图。在数据库中,有一个表 dbo.Items,其中有一个FOREIGN KEY (CategoryID) REFERENCES Categories(Id)

Items/Create的生成View有这个block,强制用户在添加新Item时从下拉列表中选择01 Category,不允许空值:

    <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 选项可用?

【问题讨论】:

    标签: c# asp.net asp.net-mvc razor


    【解决方案1】:

    Html.DropDownList() 是一个 html 辅助方法,它将生成用于呈现 SELECT 元素的 HTML 标记。它本身不会做任何“允许/不允许”的事情。

    当您提交表单时,MVC 模型验证框架会在服务器端根据您的视图模型属性和定义的数据注释进行模型验证。 helper 方法还生成所需的数据属性,jQuery validate 插件可以使用这些属性进行客户端验证。

    要允许在 SELECT 元素中不选择任何选项,请将 CategoryID 属性更改为 nullable int。如果你有视图模型,你可以在那里更新。

    public class YourViewmodel
    {
      public int? CategoryID { set;get;}
    }
    

    您还需要更新您的数据库架构,以便在 CategoryId 列中保存可空值。如果您使用的是数据库优先方法,则可以更改 db 架构(将列更改为可为空),然后重新生成实体类。

    我还建议您使用 DropDownListFor 助手

    @Html.DropDownListFor(x=>x.CategoryID,ViewBag.CountryCode as  List<SelectListItem>,
                                           "select one", new { @class = "form-control" })
    

    假设 ViewBag.CountryCode 是您在 GET 操作方法中设置的 SelectListItem 列表。

    【讨论】:

    • 这使用了我喜欢的默认绑定,并以正确的方式回答问题。谢谢!
    【解决方案2】:

    您可以使用休闲重载版本来显示“选择选项”最初...

    @Html.DropDownList("CategoryID", null, "select option", new { @class = "form-control" })
    

    每当您向 CategoryID 下拉列表添加选项时,您需要将“选择选项”添加为第一个选项,然后再休息...

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 2017-08-31
      • 1970-01-01
      • 2016-11-08
      • 2015-10-04
      • 2011-04-22
      • 2017-12-06
      • 2015-10-19
      • 1970-01-01
      相关资源
      最近更新 更多