The problem is that every time the page is updated ( Layout.cshtml ), a menu is loaded from the database.

There is an idea to create a class like Singleton, or store it in a Session object. What solution would you advise?

Model:

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

Controller:

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

Layout.cshtml

 //остальной код @{ Html.RenderAction("GetNavigationBlock", "Common"); } //остальной код 

    1 answer 1

    One simple solution is to use OutputCacheAttribute for GetNavigationBlock ():

     [ChildActionOnly] [OutputCache(Duration = int.MaxValue)] public ActionResult GetNavigationBlock() 

    Storage duration is set via the Duration property in seconds. It can also be moved to a profile (the CacheProfile property) for configuration via web.config .