How to pass Array from jQuery Ajax to the MVC 5 Action?

ajax, asp.net-mvc, asp.net-mvc-4, javascript, jquery

Solution

You need to stringify the data while sending it.

Try:

             $.ajax({
                url: "/Home/SaveQBMatter",
                type: "POST",
                data: JSON.stringify({ 'Matters': result }),
                dataType: "json",
                contentType: "application/json; charset=utf-8",
                success: function (data) {
                    alert("Success!");
                },
                error: function () {
                    alert("An error has occured!!!");
                }
            });

Problem

I try to pass my grid Data from jQuery to the MVC Action via Ajax. I have a button "Save" on my page, and this is jQuery code for click: ``` var result = []; $('#btnSave').click(function () { $('#tblMatters tbody tr.mattersRow').each(function () { var item = {}; if ($(this).find('td.qbmatter > div.dropdown').length > 0) { item.QBMatter = $(this).find('td.qbmatter > div.dropdown > a').text(); } else { item.QBMatter = $(this).find('td.qbmatter').text(); } item.Hours = $(this).find('td.hours').text(); item.Person = $(this).find('td.person').text(); if ($(this).find('td.rate > div.dropdown').length > 0) { item.Rate = $(this).find('td.rate > div.dropdown > a').text(); } else { item.Rate = $(this).find('td.rate').text(); } item.Amount = $(this).find('td.amount').text(); result.push(item); }); $.ajax({ url: "/Home/SaveQBMatter", type: "POST", data: { 'Matters': result }, dataType: "json", traditional: true, contentType: "application/json; charset=utf-8", success: function (data) { alert("Success!"); }, error: function () { alert("An error has occured!!!"); } }); }); ``` I checked the `result` array and it's correct. It contains every value that should be. In my HomeController I have the following model for my data: ``` public class QBMatter { public string QBDescription { get; set; } public string Person { get; set; } public decimal Hours { get; set; } public int Rate { get; set; } public decimal Amount { get; set; } } ``` And the following Action: ``` public ActionResult SaveQBMatter (QBMatter[] Matters) { DBAccess dba = new DBAccess(); int QBMatterID = 0; foreach (QBMatter qb in Matters) { dba.InsertQBMatter(qb.QBDescription, qb.Person, qb.Hours, qb.Rate, qb.Amount, ref QBMatterID); } return RedirectToAction("Home", "Index", "Home"); } ``` But I always getting the `"An error has occured!!!"` result... And I even don't get to the action, so error somewhere on the ajax level... What I'm doing wrong?

Original source