0
var POS = {
        AddItem: function (SKU) {
            $.ajax({
                type: 'POST',
                data: '{"code":"itm-0008", "qty":"5"},
                       {"code":"itm-0009", "qty":"1"},
                       {"code":"l1", "qty":"8"}',
                url: '@Url.Action("AddProduct", "POS")',
                success: function (data) {
                   alert("Items Successfully Added!");
                },
                error: function (req, status, errorObj) {
                    alert(errorObj.toString());
                }
            });
        }
};

This is my Controller: (It can only handle one(1) JSON "row" or object)

    [HttpPost]
    public void AddProduct(Item items)
    {
        Inventory inv = new Inventory();

        inv.Add(items.code, items.qty);
        inv.Dispose();
    }

How can i pass this multiple JSON "row" or object to a Controller?

2
  • var POS = { AddItem: function (SKU) { $.ajax({ type: 'POST', data: '[{code:"itm-0008", qty:"5"}, {code:"itm-0009", qty:"1"}, {code:"l1", qty:"8"}]', url: '@Url.Action("AddProduct", "POS")', success: function (data) { alert("Items Successfully Added!"); }, error: function (req, status, errorObj) { alert(errorObj.toString()); } }); } }; Commented Jun 29, 2015 at 2:38
  • [HttpPost] public void AddProduct(List<Item> items) { Inventory inv = new Inventory(); foreach (var _items in items) { inv.Add(_items.code, _items.qty); } inv.Dispose(); } Commented Jun 29, 2015 at 2:40

1 Answer 1

1

Change your json to an array of object:

[{"code":"itm-0008", "qty":"5"},
                   {"code":"itm-0009", "qty":"1"},
                   {"code":"l1", "qty":"8"}']

Controller:

for each(var item in items)
      inv.Add(item.code, item.qty);
Sign up to request clarification or add additional context in comments.

6 Comments

And pass List<Item> to the controller action
data:[{"code":"itm-0008", "qty":"5"}, {"code":"itm-0009", "qty":"1"}, {"code":"l1", "qty":"8"}], I tested it.. but it passes null values. Can you please tell my mistake?
the parameters in the Controller.. and also i Added this: datatype: "json", in the script..
Well the view needs to post a list
So please change your model to use List<Item>
|

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.