If I put using (Html.BeginForm(...
it works. If I call the same action from jquery, it doesn't work. I put the token generated by @Html.AntiForgeryToken()
while sending the request. It shows error "The required anti-forgery form field "__RequestVerificationToken" is not present."
What am I missing?
Below is my code:
Html:
<td id="@tdid">
@Html.AntiForgeryToken()
<input type="submit" value="Delete" onclick="deleteRecord('@Id');" />
</td>
jQuery:
function deleteRecord(id) {
var token = $("#td" + id).find('input[name="__RequestVerificationToken"]').val(); //working
if (confirm('Are you sure you want to delete this item?')) {
$.ajax({
type: "POST",
url: '@Url.Action("DeleteAsync")',
headers: {
'X-Requested-With': 'XMLHttpRequest',
RequestVerificationToken: token,
'Content-Type': 'application/json; charset=utf-8;'
},
data: JSON.stringify({
__RequestVerificationToken: token,
id: id
}),
success: function (data) {
alert("Data has been deleted.");
location.reload();
},
error: function (xhr, textStatus, thrownError) {
alert("Error occurred: " + xhr.responseText);
$("#msg").text(xhr.responseText);
}
});
}
}
Controller:
[HttpPost]
[ValidateAntiForgeryToken]
public async Task<ActionResult> DeleteAsync(int id)
{
Item item = await db.Items.FindAsync(id);
db.Items.Remove(item);
db.SaveChanges();
return Json("Record deleted", JsonRequestBehavior.AllowGet);
}