7

I'm trying to pass an array from a jQuery function to my controller. The array contains content and the id of the div holding that content.

When I check the objects which are being sent via the AJAX post in Firebug the correct values are there but after placing a breakpoint on my controller the received value is an empty List or Array or whatever type I try to set it to. I'm fairly new to using JSON to pass data to my controllers so would appreciate some help in where I'm going wrong.

jQuery function called on "submit" click. The array is globally declared in my script and is added to each time a new area is filled with content.

function postContent() {
        $.ajax({
            type: "POST",
            datatype: 'json',
            url: "/Admin/getContentArray",
            data: JSON.stringify(contentArray),
            contentType: 'application/json; charset=utf-8',
            success: function (result) {
                alert(result.Result);
            }
        });
    }

Test receiving controller

[HttpPost]
    public JsonResult getContentArray(List<Content> myPassedArray)
    {
        var data = myPassedArray;
        return this.Json(null);
    }
Mark OB
  • 492
  • 1
  • 7
  • 15

2 Answers2

5

I got this working by set the traditional property to true before making the get call. i.e.:

jQuery.ajaxSettings.traditional = true

$.get('/controller/MyAction', { vals: arrayOfValues }, function (data) {... 

I found the solution here: Pass array to mvc Action via AJAX

Community
  • 1
  • 1
John
  • 3,512
  • 2
  • 36
  • 53
1

You may take a look at the following blog post. Hopefully it will clarify things up. Basically there are two cases: ASP.NET MVC 3 where you can send JSON requests to controller action out of the box and previous ASP.NET MVC versions where you need to use a custom JsonValueProviderFactory.

Darin Dimitrov
  • 1,023,142
  • 271
  • 3,287
  • 2,928
  • Thats strange because I am using MVC 3, what data type should I set to receive this data on my controller? As stated above setting it to a list of type "Content" returns a list with the correct number of entries but just no data. – Mark OB Apr 02 '11 at 18:53
  • You set me on the right track. I set my Content model to exactly mirror the keys sent in the JSON object and there you have it, results!!! Thanks Darin – Mark OB Apr 02 '11 at 19:04