I found plenty of examples that demonstrate how to add an AntiForgeryToken to the Ajax call for POST submit method. My need, as the title suggests, is to submit a form NOT via the ajax call. Instead, I'm simply using jQuery submit() function.
What I have in my razor view file is as follows (Note: I'm using html string literal because this particular DOM needs to be dynamically attached to a separate element at a later point):
var html =
"<form id='exportPdfForm' action='" + exportUrl + "' method='post'>" +
"<input type='hidden' id='exportContent'>" +
"<input type='hidden' id='__RequestVerificationToken' value='@Html.AntiForgeryToken()'>" +
"</form>";
And, obviously, I'm using the following jQuery to submit this form:
$("#exportPdfForm").submit();
Also, using the DOM Explorer I can see the AntiForgeryToken value is properly in place:

However, when I actually submit the form, I still run into the The required anti-forgery form field "__RequestVerificationToken" is not present error. I checked out several other Q&A's but can't seem to find anything that might shed some light on my problem.
Am I missing something obvious or doing something wrong here?
EDIT (Solution)
Assigning the __RequestVerificationToken to the name attribute will fix it:
<input type='hidden' name='__RequestVerificationToken' value='...'>
This one turns out to be one of those "How did I miss that...?!" moments. While the above approach is perfectly legitimate, the only problem is that the __RequestVerificationToken has to belong to a name attribute instead of to an id as in my initial example. I tried posting my form with the fix and the problem is now gone.
Obviously this wouldn't have been an issue in the first place if I could just use the <% Html.AntiForgeryToken(); %> expression, but this particular case required an unconventional approach for the reason I stated in my initial post. So, I guess this is something to look out for!
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With