I do not know how I use the AntiForgeryToken in ajax.
I found the following answers on SO but they're not working for me:
- jQuery Ajax calls and the Html.AntiForgeryToken()
- include antiforgerytoken in ajax post ASP.NET MVC
- How to make ajax request with anti-forgery token in mvc
This is my code Html:
@using (Html.BeginForm())
{
@Html.AntiForgeryToken()
@Html.TextBoxFor(model => model.UserName, new { @class = "form-control", id = "UserName", placeholder = @CMS.Resources.Resource.UserName })
@Html.PasswordFor(model => model.Password, new { @class = "form-control", id = "Password", placeholder = @CMS.Resources.Resource.Password })
<button id="LoginButton" class="k-button" type="submit">@CMS.Resources.Resource.Signin</button>
}
JavaScript:
$('#LoginButton').click(function (e) {
if ($('form').valid()) {
var data = { UserName: $('#UserName').val(), Password: $('#Password').val() };
var token = $('[name=__RequestVerificationToken]').val();
var headers = {};
headers["__RequestVerificationToken"] = token;
$.ajax({
type: 'POST',
traditional: true,
data: JSON.stringify(data),
cache: false,
headers: headers,
dataType: 'json',
url: '@Url.Action("LoginPanel", "Account")',
contentType: "application/json; charset=utf-8",
success: function (status) {
},
error: function (status) {
alert(status);
}
});
}
e.preventDefault();
});
Controller:
[HttpPost, ValidateAntiForgeryToken]
public JsonResult LoginPanel(LoginModel model)
{
LoginStatus status = new LoginStatus();
if (HttpContext.Request.IsAjaxRequest())
{
if (ModelState.IsValid)
{
....
}
}
return Json(status, JsonRequestBehavior.AllowGet);
}
And other modes of JavaScript code that tried. By placing the value __RequestVerificationToken in the header, or in data. The error is always the same:
The required anti-forgery form field "__RequestVerificationToken" is not present.
Thank.