LaserBeak
LaserBeak

Reputation: 3285

Returning several arrays as a Json result, how can I serialize the response on the server?

When the Action method below attempts to return the Json result no data object comes back to the $.ajax function. Hence I presume I am not serializing the arrays prior to sending them off as a Json result. I need to retain the array names i.e: ProgTypes, Ages etc. So I know which array is which when the data returns from the server.

   $.ajax({
            url: '/Education/FilterLists',
            dataType: 'json',
            data: { svalues: svalues, firsttype: $firsttype },
            traditional: true,
            success: function (data) {

              //do something with data

                alert('done');
            }
        });

..

      public JsonResult FilterLists(int[] svalues, string firsttype)
        {

 //Some logic takes place and below arrays are produced

            int[] ProgTypes = programs.Select(x => x.FilterValToCatMaps.FirstOrDefault(c => c.FilterValue.FilterID == 5).FilterValueID).Distinct().ToArray();

            int[] Ages = programs.Select(x => x.FilterValToCatMaps.FirstOrDefault(c => c.FilterValue.FilterID == 4).FilterValueID).Distinct().ToArray();

            int[] Countries = programs.Select(x => x.ParentCategory.ParentCategory.ParentCategory.CatID).Distinct().ToArray();


            return Json(new { progtypes = ProgTypes, ages = Ages, countries = Countries});

        }

Upvotes: 0

Views: 253

Answers (1)

John Culviner
John Culviner

Reputation: 22964

You are attempting to retrieve JSON data via a GET request (jQuery AJAX implicitly does a GET unless you specify the "type: 'POST'" option"). ASP.NET blocks JSON returning GETs for security reasons with an exception of this message:

"This request has been blocked because sensitive information could be disclosed to third party web sites when this is used in a GET request. To allow GET requests, set JsonRequestBehavior to AllowGet."

Your success function is never getting executed because the request isn't a success. I would recommend getting FireBug for FireFox and using the 'Net' tab or use chromes built in debugger and use the 'Network' tab if you are going to be doing any web development (especially AJAX). Network errors pop right up in there and it can save you a lot of time.

You have two options at this point, change your .NET code or change your JavaScript, pick one below:

$.ajax({
    url: '/Education/FilterLists',
    dataType: 'json',
    type: 'POST', //ADD POST HERE
    data: { svalues: svalues, firsttype: $firsttype },
    traditional: true,
    success: function (data) {

      //do something with data

        alert('done');
    }
});

OR

return Json(new { progtypes = ProgTypes, ages = Ages, countries = Countries}, JsonRequestBehavior.AllowGet);

Upvotes: 1

Related Questions