javascript - Ajax.BeginForm 与 BeforeSend

标签 javascript jquery ajax asp.net-mvc

我的 MVC 网站上有几个 Ajax.BeginForm。同时,我需要处理我的 Ajax 调用的 beforeSend 事件。

所以下面的代码适用于我的手动 jquery ajax 调用,但它不适用于 Ajax.BeginForm 助手:

$.ajaxSetup({
    'beforeSend': function (xhr) {
        alert('');
    }
});

有没有办法处理 MVC Ajax.BeginForm 上的 beforeSend 事件?

----------------------------------------编辑 --------------------------------------

我需要发送前事件,因为我想更改请求 header :

'beforeSend': function (xhr) {
    securityToken = $('[name=__RequestVerificationToken]').val();
    xhr.setRequestHeader('__RequestVerificationToken', securityToken);
}

谢谢

最佳答案

我认为您正在跟踪来自 http://richiban.wordpress.com/2013/02/06/validating-net-mvc-4-anti-forgery-tokens-in-ajax-requests/ 的示例这篇文章不涉及 Ajax 表单集成的支持。我做了一些测试并找到了解决方案。

我假设您将 MVC4 与 jquery-1.9.1.jsjquery.validate.unobtrusive.jsjquery.unobtrusive-ajax.js< 一起使用 引用。

以下是我的代码

@model WebApplication1.Models.DummyModel

@{
    Layout = null;
}

<!DOCTYPE html>

<html>
<head>
    <meta name="viewport" content="width=device-width" />
    <title>Index</title>
    <script src="~/Scripts/jquery-1.9.1.js"></script>
    <script src="~/Scripts/jquery.validate.js"></script>
    <script src="~/Scripts/jquery.validate.unobtrusive.js"></script>
    <script src="~/Scripts/jquery.unobtrusive-ajax.js"></script>
</head>
<body>
    <div id="Parent"> 
        @using (Ajax.BeginForm(new AjaxOptions { HttpMethod = "post", OnBegin = "BeginClient" }))
        {
            @Html.AntiForgeryToken();
            <div>First Name</div><div>@Html.TextAreaFor(m => m.FirstName)</div>
            <div>Last Name</div><div>@Html.TextAreaFor(m => m.LastName)</div>
            <input type="submit" value="Submit" />
        }
    </div>
    <script type="text/javascript">
        function BeginClient(xhr) {
            alert("posting...");
            securityToken = $('[name=__RequestVerificationToken]').val();
            xhr.setRequestHeader('__RequestVerificationToken', securityToken);
        }
        $.ajaxSetup({
            'beforeSend': function (xhr) {
                securityToken = $('[name=__RequestVerificationToken]').val();
                alert(securityToken);
                xhr.setRequestHeader("__RequestVerificationToken", securityToken);
            }
        });
    </script>
</body>
</html>

基本上您需要利用 onBegin 事件,请参阅 http://johnculviner.com/ajax-beginform-ajaxoptions-custom-arguments-for-oncomplete-onsuccess-onfailure-and-onbegin/有清楚的解释每个事件的参数是什么。

然后在你的全局属性类中,你的代码看起来像

[AttributeUsage(AttributeTargets.Class, AllowMultiple = true)]
public class ValidateAntiForgeryTokenOnAllPostsAttribute : AuthorizeAttribute
{
    /// <summary>
    /// Executes authorization based on anti-forge token.
    /// </summary>
    /// <param name="filterContext">MVC pipeline filter context.</param>
    public override void OnAuthorization(AuthorizationContext filterContext)
    {
        var request = filterContext.HttpContext.Request;

        // Only validate POSTs
        if (request.HttpMethod == WebRequestMethods.Http.Post)
        {
            // Ajax POSTs and normal form posts have to be treated differently when it comes to validating the AntiForgeryToken
            if (request.IsAjaxRequest())
            {
                var antiForgeryCookie = request.Cookies[AntiForgeryConfig.CookieName];

                var cookieValue = antiForgeryCookie != null
                    ? antiForgeryCookie.Value
                    : null;

                AntiForgery.Validate(cookieValue, request.Headers["__RequestVerificationToken"]);
            }
            else
            {
                new ValidateAntiForgeryTokenAttribute().OnAuthorization(filterContext);
            }
        }
    }
}

通过这种方式,您仍然可以强制使用 Ajax 形式的防伪 token 。

希望这对您有所帮助。

关于javascript - Ajax.BeginForm 与 BeforeSend,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/21916560/

相关文章:

javascript - jQuery:我的下拉菜单的 getPos

javascript - AJAX : How to get the last URL in a redirect flow inside an error handler with JSONP as content-type

php - 移动文件并将文件数据保存为空白时出现问题

javascript - "RequestAnimationFrame()"FPS = 显示刷新率?这会影响性能吗?

javascript - json数据结构在一个文件中,js调用输出?

javascript - 使用 JQuery 创建同一页面事件

ajax - 使用 ajax 和 web api 进行长轮询有什么问题……它会杀死我的服务器吗?和字符串比较

javascript - 网络驱动程序错误 : No active session with ID

javascript - 生成不含 O 和 0 的大写字母和数字的随机字符串

jquery - 我们如何在不设置宽度和高度的情况下为 ListView 设置滚动条?