How to load a model in _Layout.cshtml and share it with different views?

I have an MVC4 project dedicated to Courses. Many pages in the app need to deal with a list of courses. User profiles must select a list, view index for / Courses need to pull out a list, etc.

Since this data is almost always required, I would like to download it as part of the original query, so I only need to query DB once.

I present a scenario in which data is placed in Layout.cshtml and then other views can access the model data as needed, although I do not see a clear way to achieve this. I think I can break the problem into two parts:

  • Get data loaded in Layout.cshtml
  • Access to this data from other views

I am a bit stuck in both - how can I do this job?

+4
source share
3 answers

You should use Cache or OutputCache , put this list in Partial View , and then render it wherever you need:

1) Create an Action to plunge into Partial View . This view will be cached for maximum time, then any access will not create any overhead:

 [NonAction] [OutputCache(Duration = int.MaxValue, VaryByParam = "none")] public ActionResult GetCourses() { List<Course> courses = new List<Course>(); /*Read DB here and populate the list*/ return PartialView("_Courses", courses); } 

2) Using Chache , filling out the Partial View in the same way:

 [NonAction] public ActionResult GetCourses() { List<Course> courses = new List<Course>(); if (this.HttpContext.Cache["courses"] == null) { /*Read DB here and populate the list*/ this.HttpContext.Cache["courses"] = courses; } else { courses = (List<Course>)this.HttpContext.Cache["courses"]; } return PartialView("_Courses", courses); } 

3) Mark this view on Html.Action or Html.RenderAction :

 @Html.Action("GetCourses", "ControllerName") 

or

 @{ Html.RenderAction("GetCourses", "ControllerName"); } 

Additional Caching Information: Improving Performance with Output Cache

+6
source

I have two answers because I'm not sure I understand your desire.

1) Create a static helper method:

 public static class Helper { public static List<Course> GetCourses() { return db.Courses.ToList(); } } 

Then you can name it each in a view or layout:

 @Helper.GetCourses() 

2) I prefer not to display business logic in Views or Layout . I would create a BaseController . Get List<Course> in this controller. Other controllers should inherit from BaseController . Therefore, in any controller method, you can have the same List<Course> instance.

+1
source

Save the courses in HttpContext.Current.Items , in this cache there will be elements for a single request, which is ideal for your business. or use some third-party cache components like memcache

0
source

Source: https://habr.com/ru/post/1502882/


All Articles