e-on
e-on

Reputation: 1605

Jquery ajax returning null values back to controller - MVC3

I'm using jQuery ajax to build a viewmodel list and then trying to send that viewmodel to another ActionResult in order to create PartialViews. The first part works well, and I'm able to create the viewmodel (List), but when I try to send the viewmodel back to the controller to build up the partial views, everything within the viewmodel is 0. It returns the correct number of items in the list, but it seems to lose the values.

Can anyone see if I'm missing anything here?

jQuery:

$.ajax({
    async: false,
    type: 'GET',
    dataType: "json",
    url: '@Url.Action("GetMapDetails")',
    success: function (data) {
        $.ajax({
            async: false,
            type: 'POST',
            dataType: "json",
            url: '@Url.Action("GetMapItems")',
            data: {
                list: data
            },
            success: function (list) {
                //callback
                });
            }
        });
    }
});

and the controller:

public ActionResult GetMapDetails()
{
    List<ViewModel> vm = new List<ViewModel>();

    //create viewmodel here 

    return Json(vm.ToArray(), JsonRequestBehavior.AllowGet);
}
[HttpPost]
public ActionResult GetMapItems(List<ViewModel> list)
{
    return PartialView("_MapItemsPartial", list);
}

I've tried also using contentType: 'application/json' and JSON.stringify(data) but that gave me an Invalid JSON primitive error.

Any help appreciated - thanks

Upvotes: 2

Views: 2217

Answers (1)

Darin Dimitrov
Darin Dimitrov

Reputation: 1039498

You could send them as JSON request:

$.ajax({
    async: false,
    type: 'POST',
    contentType: 'application/json',
    url: '@Url.Action("GetMapItems")',
    data: JSON.stringify({
        list: data
    }),
    success: function (result) {
        //callback
    }
});

Also notice that I have removed the dataType: 'json' parameter because your GetMapItems POST controller action doesn't return any JSON. It returns a PartialView. So I guess you did something wrong and this is not what it was meant to be returned from this controller action because from what I can see in your success callback you are expecting to manipulate JSON.

Oh, and please remove this async:false => it defeats the whole purpose of AJAX as you are no longer doing any AJAX, you are now doing SJAX.

Upvotes: 3

Related Questions