Asp.net-Mvc
添加預設的 SelectListItem
public IEnumerable<SelectListItem> GetList(int? ID) { return from s in db.List orderby s.Descript select new SelectListItem { Text = s.Descript, Value = s.ID.ToString(), Selected = (s.ID == ID) }; }我將上述內容返回到視圖並填充
DropDownList. 我想SelectListItem (0, "Please Select..")在上面的 linq 結果返回到視圖之前添加一個預設值。這可能嗎?
return new[] { new SelectListItem { Text = ... } }.Concat( from s in db.List orderby s.Descript select new SelectListItem { Text = s.Descript, Value = s.ID.ToString(), Selected = (s.ID == ID) });
當您使用 ASP.NET MVC 時,您可以通過為 HtmlHelper 的 DropDownField 方法的 optionLabel 參數指定一個值來在視圖中執行此操作 - 例如:
htmlHelper.DropDownList("customerId", selectList, "Select One");將這種類型的程式碼放在你的 UI 層可能比把它放在數據層更合適。這樣做的一個缺點是您的選擇框將有一個空字元串值,而不是“選擇一個”選項的“0”,但這並不是真正的問題,因為如果您的控制器操作,您可以將其視為空值方法可以接受相關參數的可為空的 int - 例如
public ActionResult DoSomething(int? customerId) { if(customerId != null) { // do something with the value } }