I am trying to send antiforgery token and json object via ajax call
here is my ajax call method
$("button#submit-btn").on("click", function (e) {
e.preventDefault();
//var valid = $("form#sh-post-form").valid();
var modell = { PlaceId: 1 };
var token = $('input[name=__RequestVerificationToken]').val();
$.ajax({
contentType: 'application/json; charset=utf-8',
dataType: "json",
type: "POST",
url: "/Post/SaveSharePost",
data: { __RequestVerificationToken: token, model: JSON.stringify(modell) }
});
and here is my controller
[HttpPost]
[ValidateAntiForgeryToken]
public ActionResult SaveSharePost(SharePostVM model, string retunrUrl = null)
{
if (!ModelState.IsValid)
return View(model);
return View(model);
}
When I try to send the ajax call, it gives me internal error 500 and the error message says "The required anti-forgery form field __RequestVerificationToken is not present"
How can I fix it?
Thanks guys
data: { __RequestVerificationToken: token, PlaceId: 1 }and remove thecontentTypeoption (or else itsdata: JSON.stringify({ __RequestVerificationToken: token, PlaceId: 1 }),(you cannot mix the content types). But why are you not using$('form').serialize()to serialize all the inputs including the token?$('form').serialize();serializes all your form controls within the form tag including the token.__RequestVerificationToken: tokenas part of the object. But again, why not just use.serialize()?