Validating using unobtrusive before ajax post

2020-06-04 12:25发布

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条回答
够拽才男人
2楼-- · 2020-06-04 13:23

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;
 });
});
查看更多
登录 后发表回答