2012-04-25 60 views
0

我添加的數據列表asp.net的MVC的視圖JSON結果,並在我的控制器返回它的JSON:不能循環中

List<ProductListingModels> prom = new List<ProductListingModels>(); 
ProductListingModels product = new ProductListingModels(); 

foreach (var item in ien_item) 
{ 
    if ((item.Brand.IsAuthorized == true) && ((HelperClass.ICEContact.PathBrandImages + 
    item.Brand.Image) != null)) 
    { 
    product.BrandImage = HelperClass.CheckImageUrlExist(item.Brand.Image); 
    } 
    else 
    { 
    product.BrandImage = "&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;"; 
    } 
} 

prom.Add(product); 
return Json(new 
{ 
    ja = prom.ToList() 

}, JsonRequestBehavior.AllowGet); 

這是我的看法:

$.getJSON("ProductListing/Index", data, function (product) { 
    $.each(data, function (index, proValByDep) { 
    alert(proValByDep.BrandImage); 
    }); 

});

我在firebug準備好了它,JSON效果很好。 問題:

proValByDep.BrandImage is undefined. 

任何解決方案,請。非常感謝。

+0

show wh json – Mediator 2012-04-25 08:25:47

+0

'{「ja」:[{「BrandImage」:「http:// pd:8080/Product/Brand/28.PNG」}]}' – Nothing 2012-04-25 08:32:26

回答

1

我相信proble是,你正在使用的data變量在each()方法,您傳遞給請求,而不是product參數保存返回的數據。

$.getJSON("ProductListing/Index", data, function (product) { 

    // changed data to product below and also added .ja as you want to access its value 
    $.each(product.ja, function (index, proValByDep) { 
    alert(proValByDep.BrandImage); 
    }); 
}); 
+0

非常感謝,現在效果很好。 – Nothing 2012-04-26 00:29:24

1

您可能需要在data.ja上循環,因爲它是數組,而不是直接在data上循環。

$.getJSON("ProductListing/Index", data, function (product) { 
    $.each(data.ja, function (index, proValByDep) { 
    alert(proValByDep.BrandImage); 
    }); 
}); 

或者修改服務器端直接返回數組,而不是在指定屬性包裹它ja

return Json(prom, JsonRequestBehavior.AllowGet); 
+0

我使用了第一種解決方案,它不會提醒任何人事情,我得到了一個錯誤'錯誤:一個未定義,源文件:http:// localhost/jquery.min.js' – Nothing 2012-04-25 09:20:19

+0

對於第二個解決方案:它是未定義的警報。 – Nothing 2012-04-25 09:22:05

+0

This works fine - archil 2012-04-25 10:03:34