
此控制器方法是一个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 tablefunction 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 @R_419_5998@").append(newRow); } }}解决方法 假设您已返回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中的值变量上访问此模型的属性.
总结以上是内存溢出为你收集整理的c# – 如何遍历从JsonResult方法返回的Dictionary?全部内容,希望文章能够帮你解决c# – 如何遍历从JsonResult方法返回的Dictionary?所遇到的程序开发问题。
如果觉得内存溢出网站内容还不错,欢迎将内存溢出网站推荐给程序员好友。
欢迎分享,转载请注明来源:内存溢出
微信扫一扫
支付宝扫一扫
评论列表(0条)