不引人注目的验证不适用于动态内容

我在尝试使不引人注目的 jquery 验证与通过 AJAX 调用动态加载的部分视图一起工作时遇到了问题。

我花了好几天试图让这个代码运行起来,但一无所获。

观点如下:

@model MvcApplication2.Models.test


@using (Html.BeginForm())
{
@Html.ValidationSummary(true);
<div id="res"></div>
<input id="submit" type="submit" value="submit" />
}

部分观点:

@model MvcApplication2.Models.test


@Html.TextAreaFor(m => m.MyProperty);
@Html.ValidationMessageFor(m => m.MyProperty);


<script type="text/javascript" >
$.validator.unobtrusive.parse(document);
</script>

模式:

  public class test
{
[Required(ErrorMessage= "required field")]
public int MyProperty { get; set; }
}

总监:

    public ActionResult GetView()
{
return PartialView("Test");
}

最后是 javascript:

$(doument).ready(function () {
$.ajax({
url: '/test/getview',
success: function (res) {


$("#res").html(res);
$.validator.unobtrusive.parse($("#res"));
}
});


$("#submit").click(function () {
if ($("form").valid()) {
alert('valid');
return true;
} else {
alert('not valid');
return false;
}
});

验证不起作用。即使我没有在文本框中填充任何信息,提交事件也会显示警报(‘有效’)。

但是,如果不是动态加载视图,而是使用 @Html.Partial("test", Model)在主视图中呈现部分视图(并且不进行 AJAX 调用) ,那么验证就可以正常工作。

这可能是因为如果动态加载内容,DOM 中还不存在控件。但是我调用 $.validator.unobtrusive.parse($("#res"));应该足够让验证器知道新加载的控件..。

有人能帮忙吗?

71722 次浏览

If you try to parse a form that is already parsed it won't update

What you could do when you add dynamic element to the form is either

  1. You could remove the form's validation and re validate it like this:

    var form = $(formSelector)
    .removeData("validator") /* added by the raw jquery.validate plugin */
    .removeData("unobtrusiveValidation");  /* added by the jquery unobtrusive plugin*/
    
    
    $.validator.unobtrusive.parse(form);
    
  2. Access the form's unobtrusiveValidation data using the jquery data method:

    $(form).data('unobtrusiveValidation')
    

    then access the rules collection and add the new elements attributes (which is somewhat complicated).

You can also check out this article on Applying unobtrusive jquery validation to dynamic content in ASP.Net MVC for a plugin used for adding dynamic elements to a form. This plugin uses the 2nd solution.

As an addition to Nadeem Khedr's answer....

If you've loaded a form in to your DOM dynamically and then call

jQuery.validator.unobtrusive.parse(form);

(with the extra bits mentioned) and are then going to submit that form using ajax remember to call

$(form).valid()

which returns true or false (and runs the actual validation) before you submit your form.

test this:

if ($.validator.unobtrusive != undefined) {
$.validator.unobtrusive.parse("form");
}

add this to your _Layout.cshtml

 $(function () {
//parsing the unobtrusive attributes when we get content via ajax
$(document).ajaxComplete(function () {
$.validator.unobtrusive.parse(document);
});
});

Surprisingly, when I viewed this question, the official ASP.NET docs still did not have any info about the unobtrusive parse() method or how to use it with dynamic content. I took the liberty of creating an issue at the docs repo (referencing @Nadeem's original answer) and submitting a pull request to fix it. This information is now visible in the client side validation section of the model validation topic.

I got struck in the same problem and nothing worked except this:

$(document).ready(function () {
rebindvalidators();
});


function rebindvalidators() {
var $form = $("#id-of-form");
$form.unbind();
$form.data("validator", null);
$.validator.unobtrusive.parse($form);
$form.validate($form.data("unobtrusiveValidation").options);
}

and add

// Check if the form is valid
var $form = $(this.form);
if (!$form.valid())
return;

where you are trying to save the form.

I was saving the form through Ajax call.

Hope this will help someone.

just copy this code again in end of modal code

    <script src="~/Scripts/jquery.unobtrusive-ajax.min.js"></script>
<script src="~/Scripts/jquery.validate.unobtrusive.min.js"></script>

;)