mvc 5表中的SelectList,DropDownList为空值

我使用下面的代码创建一个下拉列表

调节器

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

视图

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

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

谢谢。

使用其中一个接受optionLabel的重载

 @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" }) 

这将使用第3个参数中指定的文本添加第一个选项并使用null

  

你可以使用这个重载:

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

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

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

调节器

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

视图

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

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

调节器

 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" } )