Search code examples
jqueryajaxasp.net-mvccsrfantiforgerytoken

AntiforgeryToken Not Recognized In Ajax Call


I have a scenario where i dont need to send form data but some other data through ajax call. I have a form which contains html.AntiForgeryToken() .

This is what i tried.

var modid = $("#moduleList").val();
var data = {};
data.modid = modid;

var token = $('#frmmmenu input[name="__RequestVerificationToken"]').val();
data.__RequestVerificationToken = token;
//var dataWithToken = $.extend(data, token);
$.ajax({
    type: "POST",
    url: "Home/MainMenu",
    data: JSON.stringify(data),
    //contentType: "application/json; charset=utf-8",  // request data type
    dataType: "html",  // response data type
    success: function (msg) {

        $("#accordion").html(msg);
    },
    error: function (msg) {
        alert("Ajax Error");
    },
});

But i keep getting The required anti-forgery form field "__RequestVerificationToken" is not present. error.

Here is the Firebug Screen grab

enter image description here

Also My action method is decorated with ValidateAntiForgeryToken

[HttpPost]
[Authorize]
[ValidateAntiForgeryToken]
public ActionResult MainMenu(int modid)
{
}

What is causing this ? Any Ideas ?

EDIT : This is a MVC5 Project.


Solution

  • Found the solution.

    The culprit was

    data: JSON.stringify(data),
    

    Changed the above to

    data: data,
    

    Now Firebug shows

    enter image description here

    Hope somebody can post a solution with JSON as Url length is limited although it requires contentType application/x-www-form-urlencoded

    Thank you all for your support.