Peter
Peter

Reputation: 53

Use AntiForgeryToken in ajax - mvc5

How I can solve this problem:

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

I have read a lot of forums but a can't find out a solution. It seems the AntiForgeryToken is not send but I've got not idea how i could do it.

In my view I've include @Html.AntiForgeryToken(), my controller has [ValidateAntiForgeryToken].

 var http = new XMLHttpRequest();
        var url = "..@actionInAPP"
        var token = $('input[name="__RequestVerificationToken"]').val();
        var params =serialize(document.forms[@numForm]);
        console.log(params);

        http.open("POST", url, true);

           var form_data = new FormData(document.forms[@numForm]);
           return $.ajax({
             type: 'POST',
             url: url,
             contentType: false,
             processData: false,
             headers: { '__RequestVerificationToken': token },
             complete: function(){
                http.onreadystatechange = function () {
                     if (http.readyState == 4 && http.status == 200) {
                        window.location.reload();
                     }
                     if (http.readyState == 4 && http.status == 400) {
                        document.getElementById("@targetId").innerHTML = http.responseText;
                     }
                 }
                http.send(params);
            },
          });

The information is saved in DB but in my browser I have this 500 error POST http://localhost:xxxx/xyz/Create 500 (Internal Server Error)

what is the problem here?

Upvotes: 2

Views: 1031

Answers (2)

Peter
Peter

Reputation: 53

I got it!!! i changed the $ajax and it worked perfect

return $.ajax({
             type: 'POST',
             url, url,
             contentType: false,
             processData: false,
             data: form_data,
             Success: function(){
                http.send(params);
             },
            complete: function(http){
                if (http.readyState == 4 && http.status == 200) {
                    window.location.reload();
                }
                if (http.readyState == 4 && http.status == 400) {
                    document.getElementById("@targetId").innerHTML = http.responseText;
                }
           }
        });

Upvotes: 1

D-Shih
D-Shih

Reputation: 46219

You may put the __RequestVerificationToken in jquery $ajax.data field and,Bring your Form Data in $ajax.data field then your Controller will get the form data.

like this

  $.ajax({
        url: $(this).data('url'),
        type: 'POST',
        data: { 
            __RequestVerificationToken: token, 
            someValue: 'some value' 
        },
        success: function (result) {
            alert(result.someValue);
        }
    });

include antiforgerytoken in ajax post ASP.NET MVC

Upvotes: 1

Related Questions