Search code examples
jqueryasp.net-mvc-3jquery-post

Jquery.post with mvc 3 not return the value


What i try to do is that when a dropdownlist changes i call a jquery.post() method to get the picture using json. Here is the code for it:

$.post('@Url.Action("GetImage", "urunler")', { cId: $(this).val(), pId: prd }, function (data) {
                $(".prd-image img").attr("src", data.ImgSmall);

            });

Controller code:

[HttpPost]
        public ActionResult GetImage(string cId, string pId)
        {
            long productId = long.Parse(pId);
            long colorId = long.Parse(cId);

            var productViewModel = new ProductViewModel();

            productViewModel.PTemp = productTempRepository.Get(x => x.ColorId == colorId && x.ProductId == productId);
            productViewModel.PImage = productImageRepository.GetMany(x => x.TempId == productViewModel.PTemp.Id);

            return Json((from obj in productViewModel.PImage select new { ImgSmall = obj.ImgSmall.Remove(0,1), ImgBig = obj.ImgBig.Remove(0,1) }), JsonRequestBehavior.AllowGet);

        }

But whenever i try to set the image src "data.ImgSmall" is undefined. Where is the mistake?

Thanks


Solution

  • It seems to be you return a list as json result:

     return Json((from obj in productViewModel.PImage select new { ImgSmall = obj.ImgSmall.Remove(0,1), ImgBig = obj.ImgBig.Remove(0,1) }), JsonRequestBehavior.AllowGet);
    

    so "data" will be a list...

    if you do:

     return Json((from obj in productViewModel.PImage select new { ImgSmall = obj.ImgSmall.Remove(0,1), ImgBig = obj.ImgBig.Remove(0,1) }).First(), JsonRequestBehavior.AllowGet);
    

    Then it should work...