In my index view , for each item in the list, there is an actionlink to delete the record. The action link url is of type "/Controller/Delete/id
"
When th actionlink is clicked a modal popup asks for confirmation and then a post request is sent to the controller.
The problem is that I'm not able to send the anti forgery token with the ajax call.
This is the controller method (it's just for testing):
[HttpPost]
[ValidateAntiForgeryToken]
public ActionResult Delete(int id)
{
try
{
Group g = db.Groups.Find(id);
if (g != null)
{
db.Groups.Remove(g);
db.SaveChanges();
var url = Url.Action("IndexPartial");
return Json(new
{
success = true,
message = "deletion completed successfully",
redirectUrl = url
});
}
else
{
return Json(new
{
success = false,
message = "Not found"
});
}
}
catch (Exception ex)
{
return Json(new
{
success = false,
message = ex.Message.ToString()
});
}
}
In the Index view I've added the:
@Html.AntiForgeryToken()
the javascript code for the ajax call
$('#confirmActionBtn').on('click', function () {
var token = $('[name="__RequestVerificationToken"]').val(); // Get the AntiForgeryToken value
$.ajax({
url: actionConfirmModal.attr("data-actionUrl"),
type: 'POST',
contentType: 'application/json',
headers: {'RequestVerificationToken':token},
success: function (response) {
setupModal('result');
if (response.success) {
if (response.redirectUrl != null) {
var targetPlaceHolder = actionConfirmModal.attr("data-targetPlaceHolder");
if (targetPlaceHolder != null) {
targetPlaceHolder.load(redirectUrl);
}
else {
window.location.href = redirectUrl;
}
}
else {
//do something
}
}
else {
$('#resultMessage').text("Errore : " + response.message);
}
},
error: function (xhr, status, error) {
setupModal('result');
$('#resultMessage').text("Errore : " + error);
},
});
});
When I run the code I get the error:
The required anti-forgery form field "__RequestVerificationToken" is not present.