我有这个局部观点:
@model GeomindEnterprise.Models.LoginViewModel
<div class="row">
<div class="col-md-6 col-sm-6 col-xs-6">
<!-- /SOCIAL LOGIN -->
@using (Html.BeginForm("Login", "Account", new { ReturnUrl = ViewBag.ReturnUrl }, FormMethod.Post, new { @class = "sky-form", role = "form" }))
{
<fieldset class="nomargin">
<div class="row">
<div class="col-md-10 col-md-offset-1">
@Html.AntiForgeryToken()
@Html.ValidationSummary(true, "", new { @class = "text-danger" })
<label class="input margin-bottom-10">
<i class="ico-append fa fa-envelope"></i>
@Html.TextBoxFor(m => m.UserName, new { @placeholder = "Email" })
@Html.ValidationMessageFor(m => m.UserName, "", new { @class = "text-danger" })
</label>
<label class="input margin-bottom-10">
<i class="ico-append fa fa-lock"></i>
@Html.PasswordFor(m => m.Password, new { placeholder = "Password" })
@Html.ValidationMessageFor(m => m.Password, "", new { @class = "text-danger" })
</label>
<label class="form-group">
@Html.CheckBoxFor(m => m.RememberMe, new { @class = "col-md-1" })
@Html.LabelFor(m => m.RememberMe)
</label>
<footer>
<button type="submit" onclick="myFunction()" class="btn btn-default noradius pull-right"><i class="fa fa-check"></i> OK, LOG IN</button>
</footer>
</div>
</div>
</fieldset>
}
</div>
</div>
当我点击提交按钮时,这个javascript方法被称为:
function myFunction() {
debugger;
jQuery.ajax({
type: "POST",
url: '@Url.Action("Login", "Account")',
contentType: "application/json; charset=utf-8",
data: jQuery('form').serialize(),
datatype: "json",
success: function (data) {
debugger;
jQuery('#myModalContent').html(data);
},
error: function () {
alert("Dynamic content load failed.");
}
});
}
上面的javascript方法调用此操作:
//
// POST: /Account/Login
[HttpPost]
[AllowAnonymous]
[ValidateAntiForgeryToken]
public async Task<ActionResult> Login(LoginViewModel model, string returnUrl)
{
//some logic
}
当调用acction时,我收到此错误:
The required anti-forgery form field "__RequestVerificationToken" is not present.
我知道为什么会出现这个错误?以及如何修复它?
答案 0 :(得分:1)
删除contentType: "application/json; charset=utf-8",
ajax选项,以便您使用"application/x-www-form-urlencoded; charset=UTF-8"
时所需的默认.serialize()
(请注意,使用{{1}时请求中包含令牌})
作为旁注,您应该处理表单.serialize()
事件,以便在提交之前验证表单。从提交按钮中删除.submit()
并将脚本更改为
onclick="myFunction()"
你也有$('form').submit(function(e) {
e.preventDefault();
if (!$(this).valid) {
return; // cancel the ajax call and display error messages
}
... make ajax call
});
,但你也datatype: "json",
的事实表明你的控制器方法返回html(一个$('#myModalContent').html(data);
),而不是json,所以它应该是{{1} }(或者只是省略该选项,PartialViewResult
方法将解决这个问题)
答案 1 :(得分:0)
你想做的是。
contentType: "application/json; charset=utf-8"
通过这样做(改变了发布请求的类型),获取实际数据属性的Json内容以正确绑定到T模型类型DO NOT JSON.stringify()或 jQuery('form')。serialize()数据。
答案 2 :(得分:-1)
从表单中删除@ Html.AntiForgeryToken()。它现在将起作用。它如何打开你的攻击。 这是关于防伪标记的文章,以保护自己。