asp.net-mvc Using AntiForgeryToken with Jquery Ajax Request


Example

First off you create the form

@using (Html.BeginForm())
{
  @Html.AntiForgeryToken()
}

Action Method

[HttpPost]
[ValidateAntiForgeryToken]
public ActionResult Test(FormViewModel formData)
{
    // ...
}

Script

<script src="https://code.jquery.com/jquery-1.12.4.min.js"></script>
<script>
var formData = new FormData($('form')[0]);
$.ajax({
    method: "POST",
    url: "/demo/test",
    data: formData ,
    success: function (data) {
  console.log(data);
    },
    error: function (jqXHR, textStatus, errorThrown) {
        console.log(errorThrown);
    }
})
</script>

Make sure contentType isn't set to anything apart from application/x-www-form-urlencoded and if its not specified Jquery defaults to application/x-www-form-urlencoded