将ViewBag传递给MVC中的_Layout?

时间:2013-04-19 09:24:21

标签: asp.net-mvc-4 partial-views viewbag

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

     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>

也许我应该将此代码从_Layout添加到PartialView。问题是,如何将ViewBag数据从控制器传递到PartialView

1 个答案:

答案 0 :(得分:0)

  

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

     

是的,但我正在返回2件产品已经上架

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

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