0

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.

  • 1
    The front-end code looks good (assuming `jsonString` is not empty), I guess the issue is in the back-end – Jeremy Thille Oct 21 '21 at 10:13
  • `when I send the post request my controller shows it is empty` - Well how did you test this? Please add the relevant controller code. Also verify the request is being sent succesfull in the network tab, you can even see the data being sent in that tab – DarkBee Oct 21 '21 at 10:14
  • Is the `/Admin/Product` path relative? (as in is the `/Admin/` folder in the same folder as this JS file) – akaBase Oct 21 '21 at 10:14
  • The Controller gets called but dataToString is empty on the Controllers side. On the frontendside I see that jsonString is not empty. – Gonzo Gonzales Oct 21 '21 at 10:16

1 Answers1

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.

Grant
  • 5,709
  • 2
  • 38
  • 50
  • I checked it and in my header is the correct string. – Gonzo Gonzales Oct 21 '21 at 10:47
  • Assuming you're using Chrome do you see anything inside of the Preview / Response tabs next to Headers. Also inside of the Headers tab do you see a status code that indicates a green icon, a 20X code? – Grant Oct 21 '21 at 10:57
  • I see a 500 Internal Server Error but that's from Newtonsoft in the Controller because the value is null. – Gonzo Gonzales Oct 21 '21 at 18:45
  • @GonzoGonzales updated my answer to hopefully assist – Grant Oct 25 '21 at 10:02
  • here I found a solution for my Problem. https://stackoverflow.com/questions/46549746/using-ajax-to-post-a-view-model-which-includes-an-iformfile-property-in-mvc-core – Gonzo Gonzales Oct 26 '21 at 15:42