带有BeforeSend的Ajax.BeginForm

时间:2014-02-20 18:33:21

标签: javascript jquery ajax asp.net-mvc

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

因此下面的代码适用于我的手动jquery ajax调用,但它不适用于Ajax.BeginForm帮助程序:

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

无论如何要处理MVC Ajax.BeginForm上的beforeSend事件?

------------------------------------------- 修改 -------------------------------------

我需要之前的发送事件,因为我想更改请求标头:

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

由于

2 个答案:

答案 0 :(得分:3)

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

我假设您在引用jquery-1.9.1.jsjquery.validate.unobtrusive.jsjquery.unobtrusive-ajax.js的情况下使用MVC4。

以下是我的代码

@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格式的防伪标记。

希望这有帮助。

答案 1 :(得分:0)

对于Ajax.BeginForm,您可以使用AjaxOptions.OnBegin

@using (Ajax.BeginForm("actionName", "controllerName", new AjaxOptions() {
            OnBegin = "requestBeginHandler"})) {
    ...markup here...
}

更新。要添加新的请求标头,您可以执行以下操作:

function requestBeginHandler(ajaxContext) { 
    var request = ajaxCOntext.get_request();
    securityToken = $('[name=__RequestVerificationToken]').val();
    request.get_headers()['__RequestVerificationToken'] = securityToken;
}