在ajax发布之前使用不引人注目的验证

Cra*_*erz 5 jquery asp.net-mvc-3

所以我一直在玩Anti Forgery Token,感谢你们的进步.

我已经想出了一个合并表单值的解决方案,以及让我的ActionMethods不要反击AntiForgery令牌......我遗憾地在这个过程中破坏了验证.在忽略客户端验证/客户端验证之前,将触发AJAX帖子.服务器端工作,但我会在帖子之前挖掘一些验证..这是我正在使用的代码.

$(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;
 });
Run Code Online (Sandbox Code Playgroud)

});

所以我想我需要在$ .ajax goo之前以某种方式处理客户端验证...任何建议都可能节省我一些时间.

Mar*_*tin 19

叫这个:

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

if (!formValid) return false;
Run Code Online (Sandbox Code Playgroud)

添加到您的代码中:

$(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;
 });
});
Run Code Online (Sandbox Code Playgroud)