我有一个 JavaScript 方法,可以对 Controller 方法进行 AJAX 调用。 这个 Controller 方法是一个 JsonResult 方法,它将一个字典对象返回给我的 JavaScript。但是我对这个对象所做的任何事情(比如 dictionaryObject.count、dictionaryObejct[i].value 等)都会给我“未定义”。关于我应该如何使用这个对象的任何想法?
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);
}
}
}
最佳答案
假设您返回了一个 Dictionary<string, string>
从你的 Controller Action :
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
.
关于c# - 如何遍历 JsonResult 方法返回的字典?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/22033742/