Mr.Human
Mr.Human

Reputation: 617

Returning dictionary as JSON and successfully accessing it's contents withing JS function - C#

I have a Dictionary named finalDictionary which is created by consolidating multiple Dictionaries. This is the piece of code which I use to create this Dictionary:

Dictionary<string, Dictionary<DateTime, int>> finalDictionary= new Dictionary<string, Dictionary<DateTime, int>>();

finalDictionary.Add("Data1", listData1.ToDictionary(x => x.Date, y => y.Value));
finalDictionary.Add("Data2", listData2.ToDictionary(x => x.Date, y => y.Value));
finalDictionary.Add("Data3", listData3.ToDictionary(x => x.Date, y => y.Value));

NOTE: listData1, listData2 and listData3 are all anonymous lists which I'm converting into dictionaries in the above code.

Here's the sample format for each of these dictionaries: (let's consider for Data1)

Key : 'Data1'
Value : 
        [0] {[6/14/2015 12:00:00 AM, 1]}
        [1] {[6/21/2015 12:00:00 AM, 0]}
        [2] {[6/28/2015 12:00:00 AM, 0]}
        [3] {[7/5/2015 12:00:00 AM, 0]}
        [4] {[7/12/2015 12:00:00 AM, 0]}
        [5] {[7/19/2015 12:00:00 AM, 0]}
        [6] {[7/26/2015 12:00:00 AM, 0]}    

So each of the dates above are again Key part and those numbers are Value part.

I return this Dictionary i.e finalDictionary as a JSON result from my controller method as follows :

return Json(new { Result = "OK", Records = obj.GetDetails()}, JsonRequestBehavior.AllowGet);

But when this is returned back to my calling JS ajax it fails throwing the below Internal Server 500 error:

jqXHR = {readyState: 4, getResponseHeader: ƒ, getAllResponseHeaders: ƒ, setRequestHeader: ƒ, overrideMimeType: ƒ, …}, textStatus = "error", errorThrown = "Internal Server Error //and so on

Here's my JS code :

function loadDetails() {

    $.ajax({
        type: 'GET',
        dataType: 'json',
        contentType: "application/json; charset=utf-8",
        cache: false,
        url: _WebRoot() + '/Charts/GetDetails',
        success: function (response, textStatus, jqXHR) {
            prepareData(response.Records, 'Text Title');
        },
        error: function (jqXHR, textStatus, errorThrown) {
            alert('Error - ' + errorThrown);
        }
    });
}

What modifications do I need to make it work?

NOTE : I receive the above mentioned error after the data is returned from the Controller and reaches the JS method

Upvotes: 0

Views: 1525

Answers (1)

Mr.Human
Mr.Human

Reputation: 617

Converting the datatype of 'Key' ("Date" in my case) element to String fixed the issue. Initially the "Date" was of DateTime DataType.

Hence when I was returning my above mentioned dictionary as a JSONResult from controller the JS method throwed an error as it was unable to stringify or serialize this dictionary.

So it's advisable to change your Dictionary's 'Key' element's datatype to String or set them as Objects.

Here's the error message I was able to debug out (providing this error message as it might help other's who may face such similar issues) :

Unhandled Exception: System.ArgumentException: Type 'System.Collections.Generic. Dictionary`2[[System.Int32, mscorlib, Version=4.0.0.0, Culture=neutral, PublicKeyToken=b77a5c561934e089],[ChatData, Test, Version=1.0.0.0, Culture=neutral, PublicKeyToken=null]]' is not supported for serialization/deserialization of a dictionary, keys must be strings or objects.

Upvotes: 1

Related Questions