Search code examples
jqueryajaxasp.net-mvc-5antiforgerytoken

The required anti-forgery form field "__RequestVerificationToken" is not present


here is another hurdle for me, I want my site to remain cross-site attacks protected, I'm developing a Master/Detail form by using asp.net mvc 5 through Ajax request, So, in order to create one entry, I've to go through the process of Ajax Request, this way :

$.ajax({
        url: '/Sales/Create',
        data: JSON.stringify(salesmain),
        type: 'POST',
        contentType: 'application/json;',
        dataType: 'json',
        success: function (result) {

            if (result.Success == "1") {
                window.location.href = "/Sales/index";
            }
            else {
                alert(result.ex);
            }
        }
    });

now, it is not navigating to the Create action in the Sales Controller, as the ajax request says, and before that, it throws the following exception :

The required anti-forgery form field "__RequestVerificationToken" is not present.

I've searched a lot on google but still unsuccessful, that's why I'm here, I've read some blogs which says fetch the hidden __RequestVerificationToken field using jquery and append it to the form values, enclosing the JSON.stringify(salesmain) in a function, this way :

$.ajax({
.
.
addRequestVerificationToken(JSON.stringify(salesmain))

and the function :

function addRequestVerificationToken(data) {
data.__RequestVerificationToken = $('input[name=__RequestVerificationToken]').val();
return data;
};

Plus, I already have below code structure :

@using (Html.BeginForm())
{
  @Html.AntiForgeryToken()
  .
  .

and the attribute before the Create action :

[HttpPost]
[ValidateAntiForgeryToken]
public JsonResult Create([Bind(Include = "SalesId,ReferenceNo,SalesDate,SalesPerson")] SalesMain salesMain)
{
.
.

and also I'm using jQuery 1.5, may be it is the culprit, if not then what should I do to resolve this issue? Any HELP will be deeply appreciated, Thanks in Advance :)


Solution

  • Your addRequestVerificationToken() function does not add the token because you have already stringified the data (its no longer a javascript object so data.__RequestVerificationToken = $(...) does nothing).

    You could make this work by changing the code to

    data: JSON.stringify(addRequestVerificationToken(salesmain)),
    

    however this is unnecessary as you do not need to stringify the data. Instead remove the contentType: 'application/json;', option so that it uses the default application/x-www-form-urlencoded; charset=UTF-8' and use

    data: addRequestVerificationToken(salesmain),
    

    or better still, if you have correctly generated you view using the HtmlHelper methods and your inputs contain the correct name attribute (name="SalesId", name="ReferenceNo" etc) then you an simply use

    data: $('form').serialize(),`
    

    which will correctly serialize all inputs in your form including the token.