jQuery验证 - 通过MVC2中的ajax动态添加必填字段

时间:2010-07-30 16:31:36

标签: asp.net-mvc-2 jquery-validate

我正在尝试在MVC2中的表单上使用jQuery验证。我正在使用期货项目中的 MicrosoftMvcJQueryValidation.js

首次加载表单时,它是代表ViewViewModel,并且有三个字段经过验证。验证对他们来说非常有效。

用户可以通过ContactViewModel类表示的Ajax点击链接,该链接加载3个额外的必填字段。

我已经开始工作,以便MVC框架将正确的 window.mvcClientValidationMetadata 数据发送回浏览器和 __ MVC_EnableClientValidation __ MVC_CreateValidationOptions 正在为新添加的字段调用函数。

但是,当按下提交按钮时,只会对前3个字段进行验证。

我正在使用的模型是:

public class RepresentativeViewModel
{
    [HiddenInput(DisplayValue=false)]
    public int Id { get; set; }

    [Required(ErrorMessage = "Name is required")]
    public string Name { get; set; }

    [Required(ErrorMessage = "Telephone is required")]
    public string Telephone { get; set; }

    [Required(ErrorMessage = "Website is required")]
    public string Website { get; set; }

    public IEnumerable<ContactViewModel> ContactList { get; set; }
}

public class ContactViewModel
{
    [HiddenInput(DisplayValue = false)]
    public int Id { get; set; }

    public int RepresentativeId { get; set; }
    public RepresentativeViewModel Representative { get; set; }

    [Required(ErrorMessage="First Name is required")]
    public string FirstName { get; set; }

    [Required(ErrorMessage = "Last Name is required")]
    public string LastName { get; set; }

    [Required(ErrorMessage = "Job is required")]
    public string JobTitle { get; set; }
}

通过一些调试我在jquery.validate中找到了这个:

// check if a validator for this form was already created
var validator = $.data(this[0], 'validator');
if ( validator ) {
    return validator;
}

似乎在我通过ajax加载额外字段后,与表单关联的验证器将永远不会更新。如果我注释掉这一行:

    return validator;

然后只验证新字段。

当用户点击提交时,如何同时验证原始字段和新字段?

1 个答案:

答案 0 :(得分:0)

尝试拨打

      $(document).ajaxComplete(function (event, request, settings) {
        $.validator.unobtrusive.parse(document);
    });