Error 400 when sending a Javascript Buffer Array to a C#Action

Asked

Viewed 40 times

-1

After receiving a CSV file and reading it with the JS Filereader, I need to send the return of this reading to an Action of a C#Controller. However when sending, I get an error 400. I would like to know a way to send this data to the back end and correct this error. Below are the codes :

JS function to read CSV.

function lerCSV() {

    var reader = new FileReader();
    reader.onload = function () {

        var resultado = reader.result;

        console.log(resultado);

        $.ajax({
            url: "/Dashboard/" + productId + "/Coupons/GenerateTable",
            type: "POST",
            dataType: "json",
            contentType: 'application/json; charset=utf-8',
            data: '{resultado:'+  resultado + '}',
            success: function (result) {

                alert('Concluido');
            }

        });

    };

    //start reading the file. When it is done, calls the onload event defined above.
    reader.readAsText(planilha.files[0]);

}

Action C#

public IActionResult GenerateTable(string resultado)
{
   return Json("Concluido");
}
  • Was able to test?

  • So @Leandroangelo tested, but continues with bad request error.

  • Now I get it, you didn’t prepare your controller to receive a json

  • What I should receive as a parameter in Action?

  • Watch the answer edit, but don’t just copy and paste. Try to understand what you’re doing and what’s going on ;)

  • Managed to solve?

Show 1 more comment

1 answer

0

You are riding a Json invalid, the correct would be.

{"resultado": "seu texto"}

Change your javascript

function lerCSV() {

    var reader = new FileReader();
    reader.onload = function () {

        var resultado = reader.result;

        console.log(resultado);

        $.ajax({
            url: "/Dashboard/" + productId + "/Coupons/GenerateTable",
            type: "POST",
            dataType: "json",
            contentType: 'application/json; charset=utf-8',
            data: `{"resultado": "${resultado}"}`,
            success: function (result) {

                alert('Concluido');
            }

        });

    };

    //start reading the file. When it is done, calls the onload event defined above.
    reader.readAsText(planilha.files[0]);

}

But in that case you should also change yours Action and create a ViewModel for the serialization and deserialization of the object. And realize that the return of Controller is also not bringing a JSon valid...

[HttpPost]
public IActionResult GenerateTable([FromBody] GenerateTableRequestViewModel resultado)
{
   return Json("{ \"Status\" : \"Concluido\"}");
}

Generatetablerequestviewmodel

public class GenerateTableRequestViewModel
{
    public string Resultado {get; set;}
}

Browser other questions tagged

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