Manually bind JQuery validation after Ajax request

前端 未结 5 1334
轮回少年
轮回少年 2021-01-03 02:27

I\'m requesting an ASP.net MVC view into a live box and the view contains form fields that have been marked up with attributes to be used by JQuery\'s unobtrusive validators

相关标签:
5条回答
  • 2021-01-03 03:05

    For some reason I had to combine bjan and dfortun's answers...

    So I put this in my view:

    @{
      this.ViewContext.FormContext = new FormContext();
    }
    

    And this execute this after the ajax call finishes:

    var form = $("#EnrollmentForm");
    form.unbind();
    form.data("validator", null);
    $.validator.unobtrusive.parse(document);
    form.validate(form.data("unobtrusiveValidation").options);
    
    0 讨论(0)
  • 2021-01-03 03:13

    Another option, rather trick, which worked for me. Just add following line in the beginning of the partial view which is being returned by ajax call

    this.ViewContext.FormContext = new FormContext(); 
    

    Reference

    0 讨论(0)
  • 2021-01-03 03:14

    You may take a look at the following blog post. And here's another one.

    0 讨论(0)
  • 2021-01-03 03:16

    I had a similar issue. I had a form that was using Ajax requests to re-display a part of the form with different form fields. I used unobtrusive validation by manually doing it on the client side using the

    @Html.TextBoxFor
    

    for my text boxes. For some reason the validation works when attempting to submit with invalid fields (i.e., the text boxes get outlined in red and the appropriate error messages display with the content I put in the

    data_val_required
    

    attribute, for example.

    However, after I click a button that makes an Ajax request to modify the form with different fields and then submit again, only the red outline on the invalid fields display, but no error messages are rendered.

    bjan's trick worked for me, but I still can't see what was causing the issue. All the HTML necessary to carry out the client-side validation was there I just can't figure out why the error message attribute values wouldn't display.

    All I can think of is that the jQuery validation code doesn't make a second attempt to check the form fields after a submit was made.

    0 讨论(0)
  • 2021-01-03 03:18
    var $form = $("form");
    
    $form.unbind();
    $form.data("validator", null);
    
    $.validator.unobtrusive.parse(document);
    // Re add validation with changes
    $form.validate($form.data("unobtrusiveValidation").options);
    
    0 讨论(0)
提交回复
热议问题