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" } )
- 即使删除用户,ASP.Net Identity Identity.IsAuthenticated仍然是正确的
- .NET 4 MVC 2使用注释警告而不是错误进行validation
- MVC5和SSRS ReportViewer – 如何实施?
- ASP.NET Web API部分响应Json序列化
- 在MVC4问题中使用RenderAction(actionname,values)
- entity framework6重用数据注释
- 无效控制器时的StructureMap错误
- “IEntityChangeTracker的多个实例无法引用实体对象”
- UserManager错误 – 在上一个异步操作完成之前,在此上下文中启动了第二个操作