0

Im doing the biggest project of my life and im stocked with error, there is the story: I made a dropdownlist of countries, when you choose the country from the select list i use javascript to send countries ID to state function:

$("#Country").change(function () {
    var Index = $(this).val();
    $.ajax({
        url: '/Company/State',
        type: "POST",
        dataType: 'html',
        data: { CountryId: Index },
        success: function (data) {
            $('#State').empty();
            $('#State').append($('<option>').attr("value", "").text("Select state"));
            var state = JSON.parse(data)["state"];
            for (var i = 0; i < state.length; i++) {
                $('#State').append($('<option>').attr("value", state[i].id).text(state[i].name));
            }
        }
    });

and then my droplist doesnt work and i get the following error and my drop list doesn't show anything:

"Failed to load resource: the server responded with a status of 400 (Empty or invalid anti forgery header token.)"

and when i disable the antiforgerytoken everything works perfectly

 [HttpPost]
 [DisableAbpAntiForgeryTokenValidation]
 public string State(GetStateInput input)

there is my question:

We need the antiforgerytoken and we can not disable it, so how i overcome the error without disabling the antiforgerytoken?

  • Possible duplicate of [include antiforgerytoken in ajax post ASP.NET MVC](https://stackoverflow.com/questions/14473597/include-antiforgerytoken-in-ajax-post-asp-net-mvc) – Backs Oct 14 '17 at 14:27

1 Answers1

-1

Preferably, add this in your _Layout.cshtml or view:

@{
    SetAntiForgeryCookie();
}

Alternatively, intercept XMLHttpRequest:

(function (send) {
    XMLHttpRequest.prototype.send = function (data) {
        this.setRequestHeader(abp.security.antiForgery.tokenHeaderName, abp.security.antiForgery.getToken());
        return send.call(this, data);
    };
})(XMLHttpRequest.prototype.send);
aaron
  • 39,695
  • 6
  • 46
  • 102