I was using antiforgerytoken within my razor view, and it was working fine. Then I moved the same code to AJAX, and it has started giving weird problems.
The AJAX POST request works fine, but the action SendData()
which is called from the AJAX has a redirect to a different View (return View("Close");
), which does not work anymore. It worked perfectly fine when the SendData()
was called from the form directly.
Working code:
@using(Html.BeginForm("SendData", "Controller", FormMethod.Post)) {
@Html.AntiForgeryToken():
}
Not working code:
@using(Html.BeginForm("", "", FormMethod.Post, new
{
id = "__AjaxAntiForgeryForm"
}))
{
@Html.AntiForgeryToken()
}
JS File:
var form = $('#__AjaxAntiForgeryForm');
var token = $('input[name="__RequestVerificationToken"]', form).val();
$.ajax({
type: 'POST',
url: '/Controller/SendData',
data: {
__RequestVerificationToken: token
},
cache: false,
success: function(result) {}
});
The Action SendData() executes fine, but the redirect within this action doesn't work anymore.