unobtrusive validation not working with dynamic content

后端 未结 7 1667
一生所求
一生所求 2020-11-28 02:07

I\'m having problems trying to get the unobtrusive jquery validation to work with a partial view that is loaded dynamically through an AJAX call.

I\'ve been spending

相关标签:
7条回答
  • 2020-11-28 02:46

    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.

    0 讨论(0)
  • 2020-11-28 02:47

    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.

    0 讨论(0)
  • 2020-11-28 02:49

    test this:

    if ($.validator.unobtrusive != undefined) {
        $.validator.unobtrusive.parse("form");
    }
    
    0 讨论(0)
  • 2020-11-28 02:55

    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.

    0 讨论(0)
  • 2020-11-28 02:56

    add this to your _Layout.cshtml

     $(function () {
            //parsing the unobtrusive attributes when we get content via ajax
            $(document).ajaxComplete(function () {
                $.validator.unobtrusive.parse(document);
            });
        });
    
    0 讨论(0)
  • 2020-11-28 03:03

    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>
    

    ;)

    0 讨论(0)
提交回复
热议问题