0

我在我的模型以下屬性:ASP.NET MVC無法綁定和驗證DropDownListFor如果範圍設置和禁用JavaScript

[Required] 
    [Range(1, int.MaxValue, ErrorMessage = "Bad number")] 
    public virtual int Number { get; set; } 

我加油吧在控制器:

List<SelectListItem> items = new List<SelectListItem>(); 
// numbers is just a list with entities with an integer field Number 
items.AddRange(numbers. 
       Select(n => new SelectListItem() { Text = n.Number.ToString(), Value = n.Number.ToString() }) 
       .ToArray()); 

ViewBag.Numbers = items; 

在我看來,我有以下幾點:

  @Html.DropDownListFor(m => m.Number, ViewBag.Numbers as IEnumerable<SelectListItem>, "Select a number") 
      @Html.ValidationMessageFor(m => m.Number) 

它似乎工作正常,如果Javascript已啓用 - 當我選擇噸他的第一個項目(這是空的「選擇一個數字」),必需的驗證器踢,並不允許發佈。

但當我禁用JavaScript,然後我得到了我的觀點異常權上DropDownListFor方法調用:

The ViewData item that has the key 'Number' is of type 'System.Int32' but must be of type 'IEnumerable<SelectListItem>'. 

當我註釋掉[範圍],那麼有沒有這樣的例外,但隨後它似乎需要不起作用 - 我可以發佈空的「選擇一個數字」選項(其值=「」),我的模型通過驗證,但它不應該 - 空字符串不是一個有效的整數!爲什麼在Javascript啓用時工作正常,但服務器端失敗?

回答

3

在您的文章的行動,不要忘記重新填充ViewBag.Numbers財產,你在你的GET操作返回查看之前做了同樣的方式:

[HttpPost] 
public ActionResult SomeAction(MyViewModel model) 
{ 
    // some processing ... 

    // now repopulate the ViewBag if you intend to return the same view 
    ViewBag.Numbers = numbers 
     .Select(n => new SelectListItem { 
      Text = n.Number.ToString(), 
      Value = n.Number.ToString() 
     }) 
     .ToList(); 

    return View(model); 
} 
+0

謝謝,這個固定異常的問題。如預期的那樣,模型驗證失敗。 – JustAMartin