0

In my Search controller I have:

     public JsonResult Search(string term)
      {
         var termLower=term.ToLower();
        var pictures=_PictureRepo.GetAll();

        var productsWereSeached = _ProductRepo.GetAll().Where(x => x.Name.ToLower().Contains(term)).Select(x=> new ProductData

        {
            Name=x.Name,
            Price=x.Price,
            Id=x.Id,
            Warranty=x.Warranty,
            Picture=x.Pictures.FirstOrDefault()

        });
        ViewBag.NOfMatchedProduct = productsWereSeached.Count();
        productsWereSeached = productsWereSeached.Take(2);
        foreach (var product in productsWereSeached)
        {
            product.Picture = _PictureRepo.GetAll().Where(x => x.ProductId == product.Id).FirstOrDefault();
        }


        return Json(productsWereSeached);
    }

In my _Layout I have :

 <div>
    <input id="nOfMatchedProducts" value='@ViewBag.NOfMatchedProduct'/>
  <ul id="realPlaceForSearchItems">
 </ul>
</div>

Maybe I should put this code from _Layout to PartialView. The question would be, how to pass ViewBag data from controller to PartialView.

Vlado Pandžić
  • 4,879
  • 8
  • 44
  • 75
  • "public JsonResult Search" - so you are already calling your method in ajax, right? You don't need to use a ViewBag. – von v. Apr 19 '13 at 09:26
  • Yes, but I am returning 2 productsWereSeached (notice Take(2) part) but I need to send somehow ViewBag.NOfMatchedProduct – Vlado Pandžić Apr 19 '13 at 09:29

1 Answers1

0

"public JsonResult Search" - so you are already calling your method in ajax, right?

Yes, but I am returning 2 productsWereSeached

You already have the result and just need to show it to your targeted element:

$.get('@Url.Action("Search")',function(result){
    $("#nOfMatchedProducts").html(result.length);
});

If you want to return additional information like the total number of records searched in addition to "your filtered results", then you can pass it like this:

var totalrows = productsWereSeached.Count();
//filter your search (productsWereSeached)
return Json(new {list=productsWereSeached, totalrows });

Then do this ajax call:

$.get('@Url.Action("Search")',function(result){
    $("#nOfMatchedProducts").html(result.totalrows);
});
Community
  • 1
  • 1
von v.
  • 16,868
  • 4
  • 60
  • 84