Asp.net mvc 4 将ViewBag传递到MVC中的_布局?

Asp.net mvc 4 将ViewBag传递到MVC中的_布局?,asp.net-mvc-4,partial-views,viewbag,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)

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

     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);
    }
在我的_布局中,我有:

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

也许我应该把这个代码从
\u布局
放到
部分视图
。问题是,如何将
ViewBag
数据从控制器传递到
PartialView

“publicJSONResult搜索”-那么您已经在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);
});

“publicJSONResult搜索”-那么您已经在ajax中调用您的方法了,对吗?您不需要使用ViewBag。是的,但我返回2个产品已研究(注意拍摄(2)部分),但我需要以某种方式发送ViewBag。NOfMatchedProductNo,可以有1000个产品已研究,我总是返回两个,但在我看来,我需要数字1000。返回多少并不重要,只要返回一个IEnumerable,就可以在jquery中确定其长度。我不确定您是否理解我的意思,我得到了预期的结果。长度2!因此,如果您想返回您的列表和计数,请查看我的更新答案。我很高兴您现在理解了我,您的答案也很好,谢谢:)