Reputation: 8471
Searching a lot with regards cross-site forgery and adding them for ajax request. So here's what I have done.
Controller
[HttpPost]
[ValidateAntiForgeryToken]
public ActionResult Delete(int id = 0)
{
// Do something here
if (Request.IsAjaxRequest())
return new HttpStatusCodeResult(HttpStatusCode.OK);
return RedirectToAction("Index");
}
JS
$(function () {
$(".delete").click(function () {
var bool = confirm("Are you sure?");
var $link = $(this);
if (!bool) return false;
var token = $('input[name="__RequestVerificationToken"]').val();
var data = {};
data['__RequestVerificationToken'] = token;
$.post($(this).attr("href"), data)
.done(function () {
$link.closest("tr").fadeOut();
});
return false;
});
});
View
@Html.AntiForgeryToken()
@Html.ActionLink("Delete", "Delete", new { id = model.Id }, new { @class = "delete" })
It worked but my question is..
@Html.AntiForgeryToken()
inside a form automatically gets posted as well?@Html.AntiForgeryToken()
or not?Upvotes: 0
Views: 372
Reputation: 6366
Q: Am I doing it right?
A: Yes, this is how you should do this.
Q: Does including an @Html.AntiForgeryToken() inside a form automatically gets posted as well?
A: Yes it is, because it is of input type, so it is included in the form collection when submitting the form.
Q: What if I have so many ajax request in one page. Do I have to include just one @Html.AntiForgeryToken() or not?
A: It is enough to use just one token for the whole page.
Q: If you have simpler way, please post it or is this the simplest way
A: It's the simplest way, you should though try to make the code connected with getting the token from the DOM and setting it to your data collection reusable (by moving this to a separate function).
Upvotes: 2