How to use Ajax with Antiforgerytoken?

Asked

Viewed 1,460 times

2

Follows the code:

//AntiForgeryToken
function gettoken() {
    var token = '@Html.AntiForgeryToken()';
    token = $(token).val();
    return token;
}

Ajax and formData:

var formData = new FormData();
var file = document.getElementById("imageFile").files[0];
var file1 = document.getElementById("coverFile").files[0];

$.ajax({
    cache: false,
    type: "POST",
    url: 'ação controller',
    data: {formData, gettoken}, <- como fazer aqui
    dataType: 'json',
    contentType: false,
    processData: false,
    success: function (response) {
        if (response) {

        }
    }
    ,
    error: function (request, status, error)
    {
        alert('Error')
    }
});

Partialview:

<form id="myform">
    <div class="modal-body">

      Campos...

    </div>
    <input type="submit" class="btn btn-success" value="Criar" />
</form>

How to make Antiforgerytoken via Ajax to protect against counterfeiting ? Any solution ?

  • What exactly do you want to do? You didn’t explain anything in the question...

  • would that be? http://stackoverflow.com/questions/5507234/how-to-use-basic-auth-with-jquery-and-ajax

1 answer

4


You will need to capture the value of the token before sending, this way

var form = $('#Id-do-Formulario'); //Tanto faz a forma de capturar
var token = $('input[name="__RequestVerificationToken"]', form).val();

Example

@using (Html.BeginForm(null, null, FormMethod.Post, new { id = "__AjaxAntiForgeryForm" }))
{
    @Html.AntiForgeryToken()
}

<div id="id-da-div" data-url="@Url.Action("Index", "Home")">
    Ajax com ValidateAntiForgeryToken
</div>

<script type="text/javascript">
    $('#id-da-div').submit(function () {
        var form = $('#__AjaxAntiForgeryForm');
        var token = $('input[name="__RequestVerificationToken"]', form).val();
        $.ajax({
            url: $(this).data('url'),
            type: 'POST',
            data: { 
                __RequestVerificationToken: token, 
                formData: dadosParaEnviar 
            },
            success: function (result) {

            }
        });
        return false;
    });
</script>

Or, you can capture the value with a function

<script type="text/javascript">
    function gettoken() {
        var token = '@Html.AntiForgeryToken()';
        token = $(token).val();
        return token;
    }
</script>

And use it like this

//ajax
data: {
    __RequestVerificationToken: gettoken(),
    formData: dados
},
  • as I do with my date to send this giving error date: JSON.stringify(all services_servicos), // pass the parameters like this: date: { __Requestverificationtoken: gettoken(), all services_servicos }, // pass the parameters

  • @Denilsoncarlos what error is giving ?

  • @Denilsoncarlos, put it like this: data: { __RequestVerificationToken: gettoken(), formData: todos_servicos },

  • if I use the date: JSON.stringify(all services_service), it sends to my controller all the information contained in my "all services_service" if I put date: { __Requestverificationtoken: gettoken(), all services_service }, does not send and the error "Uncaught Syntaxerror: Unexpected token :" on the date line.

  • @Denilsoncarlos creates new post(question), what’s happening to your problem.

Browser other questions tagged

You are not signed in. Login or sign up in order to post.