Ali Sajid
Ali Sajid

Reputation: 4339

Posting JSON to controller MVC 5

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"}]

Upvotes: 0

Views: 7135

Answers (1)

Darin Dimitrov
Darin Dimitrov

Reputation: 1039378

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.

Upvotes: 1

Related Questions