如何遍历从JsonResult方法返回的Dictionary?

时间:2014-02-26 06:42:08

标签: c# javascript asp.net-mvc-4

我有一个JavaScript方法,它对控制器方法进行AJAX调用。 此控制器方法是一个JsonResult方法,它将字典对象返回给我的JavaScript。但是我对这个对象做的任何事情(比如,dictionaryObject.count,dictionaryObejct [i] .value等)给了我“undefined”。有关如何使用此对象的任何想法?

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);
        }
    }
}

1 个答案:

答案 0 :(得分:7)

假设您已从控制器操作返回Dictionary<string, string>

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

    return Json(result, JsonRequestBehavior.AllowGet);
}

会导致通过网络发送以下JSON:

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

如您所见,这并不代表javascript Array,因此没有计数,大小或长度。这只是一个带有属性的普通javascript对象。

以下是您可以在AJAX成功回调中使用这些值的方法:

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

假设您返回了Dictionary<string, SomeModel>,您显然可以在javascript中的值变量中访问此模型的属性:value.SomeProperty