Note that there are some explanatory texts on larger screens.

plurals
  1. PO
    primarykey
    data
    text
    <p>Have a look at this <a href="http://blogs.us.sogeti.com/swilliams/2009/05/14/mvc-ndash-using-antiforgerytoken-over-ajax/" rel="noreferrer">blog post</a>.</p> <blockquote> <p>Say you have an Action method like this:</p> <p><code>[AcceptVerbs(HttpVerbs.Post), ValidateAntiForgeryToken] public ActionResult DeleteAccount(int accountId) { // delete stuff }</code></p> <p>And you call it via:</p> <p><code>$.post('/home/DeleteAccount', { accountId: 1000 }, function() { alert('Account Deleted.'); });</code></p> <p>Since the POST does not include the AntiForgeryToken, it will fail.</p> <p>Fortunately, it doesn’t take much brainpower to fix this. All the client side component of AntiForgeryToken does is put the token in a basic hidden field. So, you just need to pull that data out and include it in your AJAX call.</p> <p><code>var token = $('input[name=__RequestVerificationToken]').val();</code></p> <p><code>$.post('/home/DeleteAccount', { accountId: 1000, '__RequestVerificationToken': token }, function() { alert('Account Deleted.'); });</code></p> <p>Do note that if you have multiple forms on the page with multiple AntiForgeryTokens, you will have to specify which one you want in your jQuery selector. Another gotcha is if you are using jQuery’s <code>serializeArray()</code> function, you’ll have to add it a bit differently:</p> <p><code>var formData = $('#myForm').serializeArray(); var token = $('input[name=__RequestVerificationToken]').val(); formData.push({ name: '__RequestVerificationToken', value: token });</code></p> <p><code>$.post('/home/DeleteAccount', formData, function() { alert('Account Deleted.'); });</code></p> </blockquote> <p>Update: The link has been fixed.</p>
    singulars
    1. This table or related slice is empty.
    plurals
    1. This table or related slice is empty.
    1. This table or related slice is empty.
    1. This table or related slice is empty.
    1. This table or related slice is empty.
    1. VO
      singulars
      1. This table or related slice is empty.
    2. VO
      singulars
      1. This table or related slice is empty.
    3. VO
      singulars
      1. This table or related slice is empty.
 

Querying!

 
Guidance

SQuiL has stopped working due to an internal error.

If you are curious you may find further information in the browser console, which is accessible through the devtools (F12).

Reload