开发者

Validation of DropDownListFor element in MVC3

I use jQuery Unobrtusive Validation with MVC3 to validate a DropDownListFor form element, but it doesn't work.

It validates very well if I modify DropDownListFor to Te开发者_Go百科xtBoxFor - and it also validates the other fields of the form. I have multiple DropDownListFor elements, based on what's available in the database. Thus the loop.

Here's some of my code:

ViewModel:

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; } 
}

View:

@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") 
}

Hopefully these extracts are enough to identify the error...

Any hints on why this doesnt work?


Try replacing:

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

by:

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

Notice the nullable integer that is being used. You should be using a nullable type when binding a dropdownlist that can have a non-selected value.


I figured this out myself. This seems to be a bug in MVC3, which causes collections of selectlists not to be validated. The issue has been discussed several times before, for instance:

  • http://forums.asp.net/t/1649193.aspx/1/10
  • ASP.NET MVC 3 - Validation Question

Personally, I solved it by simply manually adding data-val-required and data-val manually.

0

上一篇:

下一篇:

精彩评论

暂无评论...
验证码 换一张
取 消

最新问答

问答排行榜