2011-09-28 91 views
0

我使用jQuery Unobrtusive驗證與MVC3驗證DropDownListFor表單元素,但它不起作用。驗證MVC3中的DropDownListFor元素

它驗證得很好,如果我修改DropDownListForTextBoxFor - 它也驗證窗體的其他字段。根據數據庫中可用的內容,我有多個DropDownListFor元素。因此,循環。

下面是我的一些代碼:

視圖模型:

public class ParentViewModel 
{ 
// some other stuff here public 
List<Children> Children { get; set; } 
} 

public class ChildrenViewModel 
{ 
    public SelectList PossibleNames { get; set; } 
    [Required(ErrorMessage = "Select a name")] 
    public int ChosenNameId { get; set; } 
} 

查看:

@for (int i = 0; i < Model.Children.Count; i++) 
{ 
@Html.LabelFor(model => modell.Children[i].ChosenNameId, "Name") 
@Html.ValidationMessageFor(model => modell.Children[i].ChosenNameId) 
@Html.DropDownListFor(model => modell.Children[i].ChosenNameId, 
Model.Children[i].PossibleNames, "Choose a name") 
} 

希望這些提取物足以識別錯誤...

任何提示爲什麼這不起作用?

回答

1

嘗試更換:

[Required(ErrorMessage = "Select a name")] 
public int ChosenNameId { get; set; } 

由:

[Required(ErrorMessage = "Select a name")] 
public int? ChosenNameId { get; set; } 

注意,正在使用的可爲空的整數。綁定可具有非選定值的下拉列表時,應該使用可爲空的類型。

+0

嗯,它仍然無法正常工作。該名稱不可空;它需要被選中。 – Helge