Validating using unobtrusive before ajax post

2020-06-04 13:14发布

问题:

So I have been playing around with the Anti Forgery Token, making progress thanks to you guys.

I have figured out a solution to merge form values anf get my ActionMethods to not puke on the AntiForgery token... I have unfortunately broken validation in the process. The AJAX post fires before client side validation / client side validation is ignored. Server side works however I would dig some validation before the post.. Here is the code I am using.

$(document).ready(function () {
 $('input[type=submit]').live("click", function (event) {
     event.preventDefault();

     // Form with the AntiForgeryToken in it
     var _tokenForm = $(this).parents().find("#__AjaxAntiForgeryForm");

     // Current Form we are using
     var _currentForm = $(this).closest('form');

     // Element to update passed in from AjaxOptions
     var _updateElement = $(_currentForm).attr("data-ajax-update");

     // Serialize the array
     var arr = $(_currentForm).serializeArray();

     //Merge TokenForm with the CurrentForm
     $.merge(arr, $(_tokenForm).serializeArray());


     // The AJAX Form Post stuff
     $.ajax({
         type: "POST",
         url: $(_currentForm).attr('action'),
         data: arr,
         success: function (data) {
             $(_updateElement).html(data);
         }
     });

     return false;
 });

});

So I am thinking that I need to handle the client side validation some way before the $.ajax goo... Any suggestions would possibly save me some time.

回答1:

Call this:

var formValid = $("#FormId").validate().form();

if (!formValid) return false;

Added into your code:

$(document).ready(function () {
 $('input[type=submit]').live("click", function (event) {
     event.preventDefault();

     // Form with the AntiForgeryToken in it
     var _tokenForm = $(this).parents().find("#__AjaxAntiForgeryForm");

     // Current Form we are using
     var _currentForm = $(this).closest('form');

     var isValid = $(_currentForm).validate().form();

     if (!isValid) return false;

     // Element to update passed in from AjaxOptions
     var _updateElement = $(_currentForm).attr("data-ajax-update");

     // Serialize the array
     var arr = $(_currentForm).serializeArray();

     //Merge TokenForm with the CurrentForm
     $.merge(arr, $(_tokenForm).serializeArray());


     // The AJAX Form Post stuff
     $.ajax({
         type: "POST",
         url: $(_currentForm).attr('action'),
         data: arr,
         success: function (data) {
             $(_updateElement).html(data);
         }
     });

     return false;
 });
});