问题是每次页面刷新 ( Layout.cshtml) 时,菜单都会从数据库中加载。
有一个想法创建一个 Singleton 类型的类,或者将它存储在一个Session. 你会推荐什么解决方案?
模型:
public class Menu
{
public int Id { get; set; }
public int ParentId { get; set; }
public string Name { get; set; }
public string Action { get; set; }
public string Controller { get; set; }
public int? Parameter { get; set; }
}
public class NavBlockViewModel
{
public NavBlockViewModel()
{
MenuItems = new List<Menu>();
}
public string Name { get; set; }
public IList<Menu> MenuItems { get; set; }
}
控制器:
public class CommonController : Controller
{
[ChildActionOnly]
public ActionResult GetNavigationBlock()
{
IList<Menu> menuItems = _repo.GetMenu();
if (menuItems != null || menuItems.Count > 0)
{
var model = new NavBlockViewModel();
model.MenuItems = menuItems;
model.Name = "Главное";
return View(model);
}
return View();
}
}
布局.cshtml
//остальной код
@{ Html.RenderAction("GetNavigationBlock", "Common"); }
//остальной код
一种简单的解决方案是在 GetNavigationBlock() 上 使用OutputCacheAttribute :
存储持续时间通过Duration属性设置(以秒为单位)。它还可以移动到配置文件(CacheProfile属性)以通过web.config进行配置。