Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to traverse a Dictionary that is returned from JsonResult method?

I have a JavaScript Method that makes an AJAX call to a controller method. This controller method is a JsonResult Method that returns a dictionary object back to my JavaScript. But anything I do to this object (like, dictionaryObject.count, dictionaryObejct[i].value etc.) gives me "undefined". Any idea as to how I should use this object?

function MakeControllerMethodCallFunction(stringParam1, stringParam2) {
    // Remove all rows from table so that table can have latest data
    $('#TableModal tr').each(function (i, row) {
        var $row = $(row);

        $row.remove();
    });

    $("#TableModal thead").append("<tr><th>" + stringParam1+ " Details " + "</th></tr>");

    //Resolving the server side method URL
    var websitePath = GetRootWebSitePath();
    var getUrl = websitePath + "/Home/GetDetails";

    //Creating parameters for Ajax call
    var params = "{\"ParamOne\" : \"" + stringParam1+ "\" , \"ParamTwo\" : \"" + stringParam2+ "\" }";

    //AJAX Call
    $.ajax({
        url: getUrl,
        type: 'POST',
        dataType: 'json',
        contentType: 'application/json; charset=utf-8',
        data: params,
        success: MakeControllerMethodCallFunction_Success,
        error: function (xhr, status, thrownError) {
            alert("Get Details error");
        }
    });
}

//On Success of MakeControllerMethodCallFunction() this will be hit and values will be bind to the table
function MakeControllerMethodCallFunction_Success(dictionaryObject) {
    var Size = 0;
    if (dictionaryObject!= null) {

        Size = (dictionaryObject!= null) ? dictionaryObject.count : 0;
    }

    if (Size != null) {

        for (var i = 0; i < Size; i++) {

            var newRow = "<tr>";

            if (dictionaryObject!= null && dictionaryObject.count> 0 && dictionaryObject[i] != null) {
                newRow += "<td>" + dictionaryObject[i].name + "</td>" + "<td>" + dictionaryObject[i].value + "</td>";

            }
            else {
                newRow += "<td></td>";
            }
            newRow += "</tr>";
            $("#TableModal tbody").append(newRow);
        }
    }
}
like image 616
Abhid Avatar asked Feb 13 '23 16:02

Abhid


1 Answers

Assuming you have returned a Dictionary<string, string> from your controller action:

public ActionResult GetDetails()
{
    var result = new Dictionary<string, string>
    {
        { "key1", "value1" },
        { "key2", "value2" },
        { "key3", "value3" },
    };

    return Json(result, JsonRequestBehavior.AllowGet);
}

which would result in the following JSON being sent over the wire:

{"key1":"value1","key2":"value2","key3":"value3"}

As you can see, this doesn't represent a javascript Array, so there's no count, size or length. That's just an ordinary javascript object with properties.

And here's how you could use the values in your AJAX success callback:

function MakeControllerMethodCallFunction_Success(dictionaryObject) {
    for (var key in dictionaryObject) {
        if (dictionaryObject.hasOwnProperty(key)) {
            var value = dictionaryObject[key];
            alert(key + " -> " + value);
        }
    }
}

assuming that you returned a Dictionary<string, SomeModel> you could obviously access the properties of this model on the value variable in your javascript: value.SomeProperty.

like image 134
Darin Dimitrov Avatar answered Feb 16 '23 05:02

Darin Dimitrov