开发者

Clientside validation not working with sub-properties in ASP.NET MVC 2?

I have an object named User, with a property Name, with a Required attribute.

public class User
{
     public int Id { get; set; }

     [Required]
     public string Name { get; set; }
}

I have created a textbox, like so:

<%= Html.TextBoxFor(model => model.Name) %>

When enabling clientside validation, Name is perfectly validated client side.

However, if I create a ViewModel where User is now a property

public class UserModel
{
     public User TheUser { get; set; }
     public string SomeOtherProperty { get; set; }
}

and create my textbox

<%= Html.TextBoxFor(model => model.TheUser.Nam开发者_JAVA技巧e) %>

then clientside validation fails. The form is posted without client validation picking up the error.

It looks like the javascript window.mvcClientValidationMetadata gets filled up as before, with no noticeable difference.

What gives? Is there something i need to do?

I'm using

  • ASP.NET MVC 2 RC2 (with .NET 3.5/VS2008)
  • MicrosoftMvcJQueryValidation.js from the latest Futures download

Edit:

Upon closer inspection window.mvcClientValidationMetadata isn't filled up as it should. No ValidationRules are specified:

{"FieldName":"TheUser.Name","ReplaceValidationMessageContents":true,"ValidationMessageId":"TheUser_Name_validationMessage","ValidationRules":[]}


You should create an editor template for your class User. Load it with Html.EditorFor(model => model.User, "User"), with "User" being the name of your editor template.

The user class should be the view model for this editor template.

Then, within your editor template for user, call the editor templates for its properties.

MVC's out of the box client validation should work correctly with this.

0

上一篇:

下一篇:

精彩评论

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

最新问答

问答排行榜