[英]mvc 5 SelectList from table with blank value for 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
值
<option value="">Please Select</option>
你可以使用這個重載:
public static MvcHtmlString DropDownList(this HtmlHelper htmlHelper, string name, IEnumerable<SelectListItem> 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" }
)
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.