Nothing
Nothing

Reputation: 2642

Can not looping JSON result in the view of asp.net mvc

I added the data to the list , and return it as JSON in my controller :

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

This is in my view :

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

});

I traced it in firebug ready, the JSON works well. The problem :

proValByDep.BrandImage is undefined.

Any solution please. Thanks so much.

Upvotes: 0

Views: 172

Answers (2)

Gabriele Petrioli
Gabriele Petrioli

Reputation: 196296

I believe the proble is that you are using the data variable in the each() method, that you pass to the request, instead of the product parameter that holds the returned data..

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

Upvotes: 1

archil
archil

Reputation: 39501

You probably need to loop on data.ja as it is array, rather than on data directly.

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

Or you may change server-side to directly return array, rather than wrapping it in property named ja

return Json(prom, JsonRequestBehavior.AllowGet);

Upvotes: 1

Related Questions