0

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

12
  • data: { __RequestVerificationToken: token, PlaceId: 1 } and remove the contentType option (or else its data: 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? Commented Mar 12, 2017 at 6:11
  • so basically I can't send object and antifogery token? How can i do with $('form').seriallize()?? Commented Mar 12, 2017 at 6:18
  • Of course you can (as per the first comment - the token just needs to be part of the object). And $('form').serialize(); serializes all your form controls within the form tag including the token. Commented Mar 12, 2017 at 6:21
  • @StephenMuecke um as per your first comment, I need to send model object not "PlaceId: 1" the object will have more variables Commented Mar 12, 2017 at 6:28
  • I know! Just include __RequestVerificationToken: token as part of the object. But again, why not just use .serialize()? Commented Mar 12, 2017 at 6:29

1 Answer 1

0

you should just addd forgery token to your model like:

model.__RequestVerificationToken=token

and

$.ajax({
       contentType: 'application/json; charset=utf-8',
       dataType: "json",
       type: "POST",
       url: "/Post/SaveSharePost",
       data: {model: JSON.stringify(modell) }
});
Sign up to request clarification or add additional context in comments.

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.