【问题标题】:mvc 5 SelectList from table with blank value for DropDownListmvc 5 SelectList from table with DropDownList的空白值
【发布时间】:2016-05-07 17:43:17
【问题描述】:

我正在使用下面的代码来创建一个下拉菜单

控制器

ViewBag.Id= new SelectList(db.TableName.OrderBy(x => x.Name),"Id","Name")

查看

 @Html.DropDownList("Id", null, htmlAttributes: new { @class = "form-control" })

我的问题是如何修改SelectList 以添加一个空白项,以便为DropDownList 自动添加一个空白项。

谢谢。

【问题讨论】:

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


    【解决方案1】:

    使用接受optionLabeloverloads 之一

    @Html.DropDownListFor(m => m.ID, (SelectList)ViewBag.MyList, "Please select", new { @class = "form-control" })
    

    或者如果你不想使用强类型方法

    @Html.DropDownList("ID", (SelectList)ViewBag.MyList, "Please select", new { @class = "form-control" })
    

    这将添加带有在第三个参数中指定的文本和null 值的第一个选项

    <option value="">Please Select</option>
    

    【讨论】:

    • 感谢您的回复。所以我无法修改 SelectList 以获得想要的结果?
    • 不,但您为什么要这样做?您总是可以创建自己的 IEnumerable&lt;SelectListItem&gt; 并添加插入第一个 Text="..."Value="" 但这真的没有意义
    • 因为我想在控制器中决定没有空白值。会有没有空值的情况。
    • 我看到您刚刚编辑了您的问题,将ViewBag.MyList 更改为ViewBag.ID。我建议您遵循最佳实践,并为您绑定到的属性和 SelectList 的名称使用不同的名称
    • 在这种情况下,您必须构建自己的 IEnumerable&lt;SelectListItem&gt;SelectList 没有添加空白 (null) 选项的构造函数。
    【解决方案2】:

    你可以使用这个重载:

    public static MvcHtmlString DropDownList(this HtmlHelper htmlHelper, string name, IEnumerable<SelectListItem> selectList, string optionLabel, object htmlAttributes);
    

    其中optionLabel 是默认空项的文本。

    【讨论】:

    • 你能举个例子吗?我还想向 SelectList 添加空值“”,id 为 -1。谢谢。
    • 例如:@Html.DropDownList("Id", null, htmlAttributes: new { @class = "form-control", optionLabel: "[not selected]" }) 如果选择了文本“[未选择]”,那么您将获得 null 作为值。
    • 我收到错误““DropDownList”的最佳重载没有名为 optionLabel 的参数“
    • @ary 这应该编译:@Html.DropDownList("Id", null, htmlAttributes: new { @class = "form-control"}, optionLabel: "[not selected]")
    【解决方案3】:

    在我的项目中,这些工作:

    控制器

    ViewBag.TagHfoFlagId= new SelectList(db.TableName.OrderBy(x => x.Name),"Id","Name")
    

    查看

     @Html.DropDownList("TagHfoFlagId", null,"--Select Name--", htmlAttributes: new { @id = "tags" })
    

    【讨论】:

      【解决方案4】:

      接受的答案确实有效,但它会在视图的下拉列表中显示默认(空)值,即使您之前已经选择了一个。如果您希望在渲染视图后已选择的值显示在下拉列表中,请改用它:

      控制器

      ViewBag.Fk_Id_Parent_Table = new SelectList(db.Parent_Table, "Id", "Name", Child_Table.Fk_Id_Parent_Table);
      return View(ChildTable);
      

      查看

      @Html.DropDownList(
                   "Fk_Id_Parent_Table",
                   null, 
                   "Not Assigned", 
                   htmlAttributes: new { @class = "form-control" }
                        )
      

      【讨论】:

        猜你喜欢
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 2011-11-27
        • 1970-01-01
        相关资源
        最近更新 更多