Selthien
Selthien

Reputation: 1258

Passing JSON array in AJAX call sending null in MVC

I am trying to pass an array of json objects to my controller action and it keeps coming in as null.

Javascript Code

function UpdateSelected() {
    var items = {};

    //Loop through grid / sub grids and create json array
    $('.k-detail-row .k-grid').each(function () {
        var grid = $(this).data("kendoGrid");
        var selectedElements = grid.select();
        for (var j = 0; j < selectedElements.length; j++) {
            var item = grid.dataItem(selectedElements[j]);
            var json = item.toJSON();
            items = [].concat(items, json);
        }
    })

    //shift the first empty space out
    items.shift();

    //items is ready to send
    alert(JSON.stringify(items));
    $.ajax({
        cache: false,
        url: '/Update/GetSchematicsForSelectedVariants',
        type: 'GET',
        data: JSON.stringify(items),
        success: function (data) {
            alert("success");
        }
    });
}

The Json array looks like this:

enter image description here

Controller Action

public JsonResult GetSchematicsForSelectedVariants(List<VariantViewModel> vm)//vm coming in null
{
    return Json(_dataAccessService.GetSchematicsForMacroVariants(vm),JsonRequestBehavior.AllowGet);
}

VariantViewModel

public class VariantViewModel
{
    public string Id { get; set; }
    public string Variant { get; set; }
}

So I am not to sure what is going wrong here. My list is being passed in as null. I am not to keen on passing json objects to the controller but I believe I have the gist of what I need.

Could someone please point me in the right direction?

Upvotes: 3

Views: 1546

Answers (1)

Selthien
Selthien

Reputation: 1258

I found the issue. My data needed to be passed in the following way in my AJAX request. Can't believe I missed this honestly.

$.ajax({
        cache: false,
        url: '/Update/GetSchematicsForSelectedVariants',
        type: 'POST',
        data: {'ListOfVariants' : items},
        success: function (data) {
            alert("success");
        }
    });

Thank you everyone for your comments it helped point me in the right direction.

Upvotes: 3

Related Questions