0

I am posting JSON to my controller, but the problem is I am getting the correct count in list. i.e if JSON has two elements list has count of two but null data. Following is the code via I am making and sending the JSON. I've use TabletoJSON for making the JSON.

        $('#productsObj').click(function () {
            var rawMaterials = $('#productsTable').tableToJSON(
                        {
                            ignoreColumns: [3]
                        });

           alert(JSON.stringify(rawMaterials));
            console.log(rawMaterials);

                $.ajax({
                    url: "/Supplies/insertRawMaterial",
                    type: "POST",
                    data: JSON.stringify(rawMaterials),
                    contentType: "application/json; charset=utf-8",
                    dataType: "json",
                    traditional: true,
                    error: function (response) {
                        alert(response.responseText);
                    },
                    success: function (response) {
                        alert(data);
                        alert(response);
                    }
                });

        });

Following is the controller action method which is receiving data.

 public ActionResult insertRawMaterial(List<String> data)
    {

        if (data != null)
        {
            return Json("Success");
        }
        else
        {
            return Json("An Error Has occoured");
        }

    }

I am not sure where I am doing it wrong. Following is the JSON in alert.

[{"Raw Material Name":"Asphalt","Short Code":"AS02","Price":"20"}]
Ali Sajid
  • 3,964
  • 5
  • 18
  • 33
  • 1
    Please show us the JSON payload from your developer tools. –  Feb 05 '17 at 13:38
  • 1
    Seems like you're calling `JSON.stringify` on something that is already a JSON string. – haim770 Feb 05 '17 at 13:39
  • @haim770 I've removed JSON.strigify now getting 500 from the controller. – Ali Sajid Feb 05 '17 at 13:58
  • Heres the JSON @Amy [{"Raw Material Name":"Asphalt","Short Code":"AS02","Price":"20"}] – Ali Sajid Feb 05 '17 at 14:03
  • @Amy here is the JSON [{"Raw Material Name":"Asphalt","Short Code":"AS02","Price":"20"}] – Ali Sajid Feb 05 '17 at 14:03
  • And what does your controller method look like? –  Feb 05 '17 at 14:06
  • `List data` as your parameter means that you're expecting a list of `strings` when your JSON implies that you're posting a list of objects (`{"Raw Material Name":"Asphalt","Short Code":"AS02","Price":"20"}` will deserialize to some object). – haim770 Feb 05 '17 at 14:19
  • @haim770 So whats the best way to accept this? – Ali Sajid Feb 05 '17 at 14:22
  • @Amy insertRawMaterial in my question. – Ali Sajid Feb 05 '17 at 14:23
  • If what you really need in your controller is `List`, what is that string? Is it the string in `Raw Material Name` property? `Short Code`? – haim770 Feb 05 '17 at 14:24
  • You aren't sending a list of strings to the server. You're sending a list containing one object with some key/value pairs. –  Feb 05 '17 at 14:26
  • I've followed the top answer http://stackoverflow.com/questions/21571201/post-a-json-object-to-mvc-controller-with-jquery-and-ajax – Ali Sajid Feb 05 '17 at 14:28

1 Answers1

1

You cannot possibly expect to map this complex JSON structure to a list of strings (List<String>) that your controller action currently takes as parameter:

[{"Raw Material Name":"Asphalt","Short Code":"AS02","Price":"20"}]

So you may start by defining the appropriate view models that will reflect this structure (or almost, see the massaging technique required below):

public class MaterialViewModel
{
    public string Name { get; set; }

    public string ShortCode { get; set; }

    public decimal Price { get; set; }
}

which your controller action will take as parameter:

public ActionResult insertRawMaterial(IList<MaterialViewModel> data)
{
    ...    
}

and finally massage your data on the client to match the correct property names (name, shortCode and price of course):

// we need to massage the raw data as it is crap with property names
// containing spaces and galaxies and stuff
var massagedRawMaterials = [];

for (var i = 0; i < rawMaterials.length; i++) {
    var material = rawMaterials[i];
    massagedRawMaterials.push({
        name: material['Raw Material Name'],
        shortCode: material['Short Code'],
        price: material['Price']
    });
}

$.ajax({
    url: "/Supplies/insertRawMaterial",
    type: "POST",
    data: JSON.stringify(massagedRawMaterials),
    contentType: "application/json; charset=utf-8",
    ...

This being said, if the client side library you are currently using produces such undeterministic property names, you might consider replacing it with something more appropriate.

Darin Dimitrov
  • 1,023,142
  • 271
  • 3,287
  • 2,928