如何将模型加载到_Layout.cshtml并在各种视图之间共享?

Rob*_*ous 5 asp.net-mvc asp.net-mvc-3 asp.net-mvc-4

我有一个处理"课程"的MVC4项目.整个应用程序中的许多页面需要处理课程列表 - 用户配置文件需要提取列表,/课程的索引视图需要提取列表等.

由于这个数据几乎总是需要的,我想把它作为初始请求的一部分加载,所以我只需要一次查询数据库.

我想象一种情况,数据放在Layout.cshtml中,然后其他视图可以根据需要访问Model数据,尽管我没有看到实现这一目标的明确方法.我想我可以把问题分成两部分:

  1. 获取加载到Layout.cshtml中的数据
  2. 从其他视图访问此数据

我对这两方面都有点困惑 - 我怎么才能做到这一点?

Fal*_*als 7

您应该使用CacheOutputCache将此列表放入a中Partial View,然后在需要的任何位置呈现它:

1)创建一个Action傀儡Partial View.此视图将缓存最长持续时间,然后任何访问都不会产生任何开销:

[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);
}
Run Code Online (Sandbox Code Playgroud)

2)以相同的方式使用Chache填充Partial View:

[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);
}
Run Code Online (Sandbox Code Playgroud)

3)通过Html.Action或渲染此视图Html.RenderAction:

@Html.Action("GetCourses", "ControllerName")
Run Code Online (Sandbox Code Playgroud)

要么

@{ Html.RenderAction("GetCourses", "ControllerName"); }
Run Code Online (Sandbox Code Playgroud)

有关缓存的更多信息:使用输出缓存提高性能