0

在我的搜索控制器中,我有:

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

在我的 _Layout 我有:

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

也许我应该把这段代码从_LayoutPartialView. 问题是,如何将ViewBag数据从控制器传递到PartialView.

4

1 回答 1

0

“公共 JsonResult Search” - 所以你已经在 ajax 中调用你的方法了,对吧?

是的,但我要退回 2 个产品WereSeached

您已经有了结果,只需要将其显示给您的目标元素:

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

如果您想返回附加信息,例如除了“您的过滤结果”之外的搜索记录总数,那么您可以像这样传递它:

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

然后做这个ajax调用:

$.get('@Url.Action("Search")',function(result){
    $("#nOfMatchedProducts").html(result.totalrows);
});
于 2013-04-19T09:33:04.567 回答