Ajax with Antiforgerytoken does not pass the data

Asked

Viewed 163 times

0

I’m having trouble putting the AntiForgeryToken on my date of json. Follow the code that I pass the information from my data to the controller hassle-free.

 var todos_servicos = {
        ServicoFornecedor,
        ServicoDesabilitado: $("#ServicoDesabilitado").val(),
        CodigoInterno: $("#CodigoInterno").val(),
        Descricao: $("#Descricao").val(),
        Observacoes: $("#Observacoes").val()
    };

    $.ajax({
        url: '/ServicosTerceiros/SalvarServicos', 
        dataType: "json", 
        type: "POST",
        contentType: 'application/json; charset=utf-8',
        cache: false, 
        data: JSON.stringify(todos_servicos), // passar os parametros
        success: function (data) {

To recover the AntiForgeryToken did so:

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

Now when I use the date to send the token presents me the following error:

"Failed to load Resource: the server responded with a status of 500 (Internal Server Error)"

I’ve made several attempts on my date, follow them:

  var jsonString = JSON.stringify(todos_servicos);
    $.ajax({
        url: '/ServicosTerceiros/SalvarServicos', 
        dataType: "json",
        type: "POST", 
        contentType: 'application/json; charset=utf-8', 
        cache: false, 
        data: { __RequestVerificationToken: gettoken(), jsonString }, // passar os parametros
        success: function (data) {

In my controller:

[ValidateAntiForgeryToken]
[HttpPost]
public ActionResult SalvarServicos(DTO.ServicosTerceiros jsonString)
{
    // codigo
}

Statement in view:

@Html.AntiForgeryToken()
@Html.ValidationSummary(true, "", new { @class = "text-danger" })
  • In your action you put [ValidateAntiForgeryToken] ?

  • yes, I updated my question

1 answer

0

in the ajax upload, try to pass like this

$.ajax({
    url: '/ServicosTerceiros/SalvarServicos', 
    dataType: "json",
    type: "POST", 
    contentType: 'application/json; charset=utf-8', 
    cache: false, 
    data: JSON.stringify({ 
            __RequestVerificationToken: gettoken(), 
            jsonString: todos_servicos
    }),
    success: function (data) { ...

Browser other questions tagged

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