Pass JSON.stringify to Controller

Asked

Viewed 684 times

2

I am trying to pass a table via JSON.stringify, in ajax, is receiving the data perfectly, but I cannot pass to the controller. I’m passing that way:

function enviarDados(produtos) {

    $.ajax({
        method: "POST",
        url: '@Url.Action("Novo1","produtos")',
        contentType: 'application/json',
        dataType: 'json',
        data: JSON.stringify(produtos)

    });
}

However in the controller, I always get the list null, I’ve tried several ways, and none receives the values, always comes in null.

[HttpPost]
public IActionResult Novo1(List<PedidosProdutosF> produtos, NovoViewModel model)
{
}

I cannot pass JSON.stringify to controller in . NET CORE ?

EDIT

Class PedidosProdutosF:

[Key]
    public int Id { get; set; }
    public int ProdutoID { get; set; }
    public Produto Produto { get; set; }
    public string CodigoProduto { get; set; }
    [Display(Name = "Quantidade")]
    public int Qtd { get; set; }
    [Display(Name = "Preço Unitário")]
    public float PrecoUnitario { get; set; }
    [Display(Name = "Desconto em %")]
    public float DescontoP { get; set; }
    [Display(Name = "Desconto em R$")]
    public float DescontoV { get; set; }
    public int ICMS { get; set; }
    public float IPI { get; set; }
    public float ISS { get; set; }
    [Display(Name = "Data da Entrega")]
    public DateTime DataEntrega { get; set; }
    public int QtdFalta { get; set; }
    public float Total { get; set; }
    public float Aliquota { get; set; }
    public float VICMS { get; set; }
    public float VIPI { get; set; }
    public float VISS { get; set; }
    public int ? PedidoFornecedorId { get; set; }
    public PedidoFornecedor PedidoFornecedor { get; set; }

I made a console.log(JSON.stringify(produtos));

He returns the data to me, as follows:

[
  {
      "CodigoProduto":"P00062",
      "DescricaoProduto":"Descrição 62",
      "Qtd":"1",
      "PrecoCusto":"29,00",
      "DescontoP":"0,00",
      "DescontoV":"0,00",
      "Total":"29,00",
      "ICMS":"1",
      "AliquotaICMS":"0,00",
      "vICMS":"0,00",
      "ISS":"0,00",
      "vISS":"0,00",
      "IPI":"0,00",
      "vIPI":"0,00",
      "Qtdfalta":"",
      "ProdutoID":""
  }
]

Here is how I pass data from table to ajax, to be received in controller:

 $("#btn-enviar").click(function () {
    var produtos = [];

    $('.item').each(function () {
        var entidade = {
            CodigoProduto: $(this).children()[0].innerText,
            DescricaoProduto: $(this).children()[1].innerText,
            Qtd: $(this).children()[2].innerText,
            PrecoCusto: $(this).children()[3].innerText,
            DescontoP: $(this).children()[4].innerText,
            DescontoV: $(this).children()[5].innerText,
            Total: $(this).children()[6].innerText,
            ICMS: $(this).children()[7].innerText,
            AliquotaICMS: $(this).children()[8].innerText,
            vICMS: $(this).children()[9].innerText,
            ISS: $(this).children()[10].innerText,
            vISS: $(this).children()[11].innerText,
            IPI: $(this).children()[12].innerText,
            vIPI: $(this).children()[13].innerText,
            Qtdfalta: $(this).children()[15].innerText,
            ProdutoID: $(this).children()[16].innerText,
        };
           produtos.push(entidade);
    });
    enviarDados(produtos);
});
  • You tried to send only the data: produtos? can add an example of the generated Json and its Request class?

  • I tried data:products, but it returns error, updated the question with the class, and the Json example.

  • I can’t do some Agra tests, but I found this in the OS, it might help you: https://stackoverflow.com/questions/13779043/post-json-array-to-mvc-controller

  • I’m doing tests with these examples, but so far, no success.

  • I edited with the part that I send the table data to ajax.

  • @marianac_costa, you posted a console print.log(products), put the pure TXT so that I can simulate here inside my Javascript?

  • [{"CodigoProduto":"P00062","DescricaoProduto":"Descrição 62","Qtd":"1","PrecoCusto":"29,00","DescontoP":"0,00","DescontoV":"0,00","Total":"29,00","ICMS":"1","AliquotaICMS":"0,00","vICMS":"0,00","ISS":"0,00","vISS":"0,00","IPI":"0,00","vIPI":"0,00","Qtdfalta":"","ProdutoID":""}]

  • @Leonardobonetti is there.

  • @marianac_costa did tests on ASP.NET MVC 4 and 5 and worked perfectly, but I did the test by passing the direct string, does so for test effect, when you create the variable produtos attribute to it this value var produtos = [{ "CodigoProduto": "P00062", "DescricaoProduto": "Descrição 62", "Qtd": "1", "PrecoCusto": "29,00", "DescontoP": "0,00", "DescontoV": "0,00", "Total": "29,00", "ICMS": "1", "AliquotaICMS": "0,00", "vICMS": "0,00", "ISS": "0,00", "vISS": "0,00", "IPI": "0,00", "vIPI": "0,00", "Qtdfalta": "", "ProdutoID": "" }]; and test by sending AJAX

  • I did the test and it didn’t work, will the problem is in CORE ?

  • I think so Martian, I’ll check if there’s anything related

  • @marianac_costa atlera List<PedidosProdutosF> produtos for [FromBody]List<PedidosProdutosF> produtos

  • It returns error, This page is not working If the problem continues, please contact the owner of the site.

Show 8 more comments

2 answers

2


Check the data of your model with the data being passed in your JSON. You should pass values to all fields that do not accept null in your model. Another point is that in your JSON you have fields that have different model names, such as the field AliquotaICMS that is in JSON has the name Aliquota in the model.

Data types must also be respected when passing the Json object in the Ajax request, so use the parseInt, parseFloat when mounting your object.

$("#btn-enviar").click(function () {
    var produtos = [];

    $('.item').each(function () {
        var entidade = {
            CodigoProduto: $(this).children()[0].innerText,
            //Não existe o campo DescricaoProduto na model, então retirei do Json
            //DescricaoProduto: $(this).children()[1].innerText,
            Qtd: parseInt($(this).children()[2].innerText),
            PrecoUnitario: parseFloat($(this).children()[3].innerText),
            DescontoP: parseFloat($(this).children()[4].innerText),
            DescontoV: parseFloat($(this).children()[5].innerText),
            Total: parseFloat($(this).children()[6].innerText),
            ICMS: parseInt($(this).children()[7].innerText),
            Aliquota: parseFloat($(this).children()[8].innerText),
            vICMS: parseFloat($(this).children()[9].innerText),
            ISS: parseFloat($(this).children()[10].innerText),
            vISS: parseFloat($(this).children()[11].innerText),
            IPI: parseFloat($(this).children()[12].innerText),
            vIPI: parseFloat($(this).children()[13].innerText),
            Qtdfalta: parseInt($(this).children()[15].innerText),
            ProdutoID: parseInt($(this).children()[16].innerText),
            DataEntrega: '2018-08-25',
            Id: 1
        };

           produtos.push(entidade);
    });

    enviarDados(produtos);
});

In his Controller add [FromBody] before your list of products, to inform that these values are coming from the body of the request POST:

[HttpPost]
public IActionResult Novo1([FromBody]List<PedidosProdutosF> produtos)
  • I tried to do so, and it returns me the following error: An unhandled Exception occurred while Processing the request. Argumentnullexception: Value cannot be null. Continues to blank. I edited the question in the form I took the table data.

  • Gave error, returns the following error: If the problem continues, contact the owner of the site. HTTP ERROR 415

  • But now comes the parameter produtos?

  • Try changing your ajax call dataType: 'json', for dataType: 'text' and contentType: 'application/json' for contentType: 'application/json; charset=utf-8',

  • It does not get to enter, I put the breakpoint, and it does not enter, already returns the error. I changed to text and still the same problem happens.

  • Mariana, I don’t know where you take the Novoviewmodel object, but take it out of the parameters, there is no way the controller can receive two complex types of the request body, unless both are inside a viewmodel

  • Even though it won’t, the same error happens. There is some other way that I can pass this table to the action ?

  • @Gustavosantos I tested with the model and worked here

  • Mariana, try to change your model to stay with the properties that exist in your Json. From what I’ve seen here, your model doesn’t have all the fields that exist in your Json, for example: Descricaoproduct and Precocost (among others) do not exist in the model.

  • Passing the parameters direct @Pedropaulo ?

  • Put in your model Ordered the parameters that are missing in Json, but the controller you leave so: [HttpPost]&#xA;public IActionResult Novo1([FromBody]List<PedidosProdutosF> produtos, NovoViewModel model)

  • When I put [FromBody] it returns me error, the page does not load.

  • Which error occurs?

  • If the problem continues, please contact the website owner. HTTP ERROR 415. Products come blank anyway.

  • Turn your ajax to dataType: 'json' and contentType: 'application/json'

  • @Pedropaulo I came back, I did the test with the sem, and still gave.

Show 12 more comments

0

You are missing in two points, in the name of some attributes and in their type, for example you are sending in your JSON vICMS, but in your model this ICMS, and in the case of all attributes float and int you must use the parseFloat and parseInt respectively before sending JSON, then you will have no problems, and the parameter NovoViewModel your method is not being used and you should remove it.

Browser other questions tagged

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