[英]How to make @Html.DropDownList() allow null
我使用 Visual Studio 從數據庫自動生成控制器和視圖。 在數據庫中,有一個表 dbo.Items,它有一個FOREIGN KEY (CategoryID) REFERENCES Categories(Id)
為 Items/Create 生成的 View 有這個塊,它強制用戶在添加新 Item 時從下拉列表中選擇 01 類別,不允許空值:
<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 選項可用?
Html.DropDownList()
是一個 html 輔助方法,它將生成用於呈現 SELECT 元素的 HTML 標記。 它本身不做任何“允許/不允許”的事情。
當您根據視圖模型屬性和在其上定義的數據注釋提交表單時,MVC 模型驗證框架會在服務器端進行模型驗證。 helper 方法還生成所需的數據屬性,jQuery 驗證插件可以使用這些屬性進行客戶端驗證。
要允許在 SELECT 元素中不選擇任何選項,請將CategoryID
屬性更改為可為空的 int。 如果你有一個視圖模型,你可以在那里更新。
public class YourViewmodel
{
public int? CategoryID { set;get;}
}
您還需要更新數據庫架構以在CategoryId
列中保存可為空的值。 如果您使用數據庫優先方法,您可以更改數據庫架構(將列更改為可為空),然后重新生成實體類。
我還建議您使用DropDownListFor
助手
@Html.DropDownListFor(x=>x.CategoryID,ViewBag.CountryCode as List<SelectListItem>,
"select one", new { @class = "form-control" })
假設ViewBag.CountryCode
是您在 GET 操作方法中設置的SelectListItem
列表。
您可以使用休閑重載版本最初顯示“選擇選項”...
@Html.DropDownList("CategoryID", null, "select option", new { @class = "form-control" })
並且每當您向 CategoryID 下拉列表添加選項時,您都需要將“選擇選項”添加為第一個,然后再添加......
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.