asp.net-mvc-3 - 在 ajax post 之前使用 unobtrusive 进行验证

标签 asp.net-mvc-3 jquery

所以我一直在玩弄防伪 token ,making progress谢谢你们。

我已经找到了一个解决方案来合并表单值,并让我的 ActionMethods 不会在 AntiForgery token 上呕吐...不幸的是,我在此过程中破坏了验证。 AJAX post 在客户端验证之前触发/客户端验证被忽略。服务器端可以工作,但是我会在发布之前进行一些验证。这是我正在使用的代码。

$(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;
 });

});

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

最佳答案

调用此:

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

if (!formValid) return false;

添加到您的代码中:

$(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;
 });
});

关于asp.net-mvc-3 - 在 ajax post 之前使用 unobtrusive 进行验证,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/7272232/

相关文章:

javascript - 检查对象是否具有具有特定值的属性

asp.net-mvc - (MVC 3 Razor) - 循环遍历 3 列 div 的更简单方法

c# - 无法将指定的节点作为该节点的有效子节点插入,因为指定的节点类型错误

asp.net-mvc - 使用 Ajax 的 ASP.NET MVCContrib 网格

.net - 客户端表单验证不适用于使用 MetadataType 的 jquery 向导

php - jQuery - 找不到 ajax url

asp.net-mvc - ASP.NET MVC : Custom Html Helpers in Razor

javascript - Jquery 映射数组键和值

javascript - 查找 div 中第一次出现的类

javascript - 将 PopUp 从后台移动到前台