我的 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.js
、jquery.validate.unobtrusive.js
和 jquery.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/