Asp.net-Mvc

在 DropDownList 中驗證所需的選擇

  • January 12, 2011

我的視圖模型定義了必須顯示為組合框的屬性。屬性定義為:

[Required]
public int Processor { get; set; }

DropDownListFor用來渲染組合框:

<%=Html.DropDownListFor(r => r.Processor, Model.Processors, Model.Processor)%>

Model.Processors包含IEnumerable<SelectListItem>一個特殊項目,定義為:

var noSelection = new SelectListItem
 {
   Text = String.Empty,
   Value = "0"
 };

現在我需要向我的組合框添加驗證,以便使用者必須選擇不同的值,然後選擇“noSelection”。我希望進行一些配置,RequiredAttribute但它沒有預設值設置。

這個怎麼樣:

[Required]
public int? Processor { get; set; }

然後:

<%= Html.DropDownListFor(
   x => x.Processor, Model.Processors, "-- select processor --"
) %>

在你的 POST 動作中

[HttpPost]
public ActionResult Index(MyViewModel model)
{
   if (ModelState.IsValid)
   {
       // the model is valid => you can safely use model.Processor.Value here:
       int processor = model.Processor.Value;
       // TODO: do something with this value
   }
   ...
}

現在您不再需要手動添加noSelection項目。只需使用適當的DropDownListFor重載。

引用自:https://stackoverflow.com/questions/4672289