2

Проблема в том, что при каждом обновлении страницы (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();
    }
}

Layout.cshtml

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

1 ответ 1

4

Один из простых вариантов решения - использовать OutputCacheAttribute для GetNavigationBlock():

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

Длительность хранения задаётся через свойство Duration в секундах. Также она может быть вынесена в профиль (свойство CacheProfile) для настройки через web.config.

Ваш ответ

By clicking “Отправить ответ”, you agree to our terms of service and acknowledge that you have read and understand our privacy policy and code of conduct.

Всё ещё ищете ответ? Посмотрите другие вопросы с метками или задайте свой вопрос.