Empresas
Empregos
  • Sobre nós
  • Soluções
    • Publicação de vagas
      Publique sua vaga e receba candidatos qualificados em 48h.
    • Avaliações de candidatos
      Mais de 500 testes técnicos e psicológicos, mais anti-fraude.
    • Headhunting
      Busca executiva personalizada do início ao fim.
    • Folha de Pagamento + EOR
      Dispersão de folha e EOR em mais de 15 países da LATAM.
  • Preços
  • Empregos

0

105
Visualizações
AJAX Post call no data

Hello wenn i want to send a post request to my Controller there is no data. I tried to log my Json file and there is something. But when I send the post request my controller shows it is empty.

Here is my call:

var item = {};
        var jsonObj = [];

        item["ProductCategoryId"] = i;
        item["Name"] = txtName;
        item["Description"] = txtDescription;
        item["Price"] = txtPrice;
        item["Stock"] = txtStock;
        item["ProductCategory"] = txtProductCategory;
        item["Image"] = await getAsByteArray(txtImage);
        jsonObj.push(item);

        var jsonString = JSON.stringify(jsonObj);
        console.log("jsonString : " + jsonString);

        $.ajax({
            url: "/Admin/SaveProductToDB",
            type: "POST",
            data: { dataToSend: jsonString},
            success: function (data) {
                if (data.status == "Success") {
                    BootstrapDialog.show({
                        title: 'Success!',
                        message: "Data Updated Successfully!",
                        buttons: [{
                            label: 'OK',
                            action: function (dialog) {
                                window.location.href = "/Admin/Product";
                                removeProdData(i);
                                $("#btnAddProd").attr("disabled",false);
                                dialog.close();
                            }
                        }]
                    });
                }

            }
        });

    //Here I make a breakpoint but my string is empty
        public JsonResult SaveProductToDB(string dataToSend)
    {
         List<Product> _List = Newtonsoft.Json.JsonConvert.DeserializeObject<List<Product>>(dataToSend);
    }

the getAsByteArray

async function getAsByteArray(file) {
    return new Uint8Array(await readFile(file))
}

function readFile(file) {
    return new Promise((resolve, reject) => {
        // Create file reader
        let reader = new FileReader()

        // Register event listeners
        reader.addEventListener("loadend", e => resolve(e.target.result))
        reader.addEventListener("error", reject)

        // Read file
        reader.readAsArrayBuffer(file)
    })
}

I found out if I remove the Image. that the controller is then able to resize it. Thanks for the help so far. So I need to look at this place where the problem is.

about 4 years ago · Juan Pablo Isaza
1 Respostas
Responde à pergunta

0

You are checking against data.status as if it's a given that it exists. Just console.log(data) instead and you will see whether or not status is being returned.

Also, if you open the Network tab in Chrome you can click on the post request & see if your headers are going through accurately and also click on 'Preview' to see an unfiltered result from the controller.

You might want to modify your code to catch errors for debugging, ie:

     $.ajax({
            url: "/Admin/SaveProductToDB",
            type: "POST",
            data: { dataToSend: jsonString},
            success: function (data) {
                if (data.status == "Success") {
                    BootstrapDialog.show({
                        title: 'Success!',
                        message: "Data Updated Successfully!",
                        buttons: [{
                            label: 'OK',
                            action: function (dialog) {
                                window.location.href = "/Admin/Product";
                                removeProdData(i);
                                $("#btnAddProd").attr("disabled",false);
                                dialog.close();
                            }
                        }]
                    });
                }
            },
            error:function (xhr, ajaxOptions, thrownError) {
                // Set up whatever error reaction you want, here. ie:
                console.log('An error was encountered.');
                alert(xhr.status);
                alert(thrownError);
            }
        });

Another tip is to validate empty data being submitted prior to the Ajax call, so you only touch the backend server when your data is valid - to avoid an error.

about 4 years ago · Juan Pablo Isaza Relatório
Responde à pergunta
Encontrar trabalhos remotos

Descubra a nova forma de encontrar um emprego!

melhores empregos
Principais categorias de trabalho
Empresas
Postar vaga Preços Comercial
Jurídico
Termos e Condições Política de privacidade
© 2026 PeakU Inc. All Rights Reserved.
Andres GPT
Recomende algumas ofertas para mim
Preciso de ajuda