Abh*_*hid 4 javascript c# 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);
}
}
}
Run Code Online (Sandbox Code Playgroud)
假设您Dictionary<string, string>已从控制器操作返回a :
public ActionResult GetDetails()
{
var result = new Dictionary<string, string>
{
{ "key1", "value1" },
{ "key2", "value2" },
{ "key3", "value3" },
};
return Json(result, JsonRequestBehavior.AllowGet);
}
Run Code Online (Sandbox Code Playgroud)
这将导致通过网络发送以下JSON:
{"key1":"value1","key2":"value2","key3":"value3"}
Run Code Online (Sandbox Code Playgroud)
如您所见,这并不代表javascript Array,因此没有计数,大小或长度.这只是一个具有属性的普通javascript对象.
以下是如何使用AJAX成功回调中的值:
function MakeControllerMethodCallFunction_Success(dictionaryObject) {
for (var key in dictionaryObject) {
if (dictionaryObject.hasOwnProperty(key)) {
var value = dictionaryObject[key];
alert(key + " -> " + value);
}
}
}
Run Code Online (Sandbox Code Playgroud)
假设您返回了一个,Dictionary<string, SomeModel>您显然可以在javascript中的value变量中访问此模型的属性:value.SomeProperty.
| 归档时间: |
|
| 查看次数: |
1155 次 |
| 最近记录: |