您应该使用Cache
or OutputCache
,将此列表放入 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);
}
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);
}
Html.Action
3)通过或呈现此视图Html.RenderAction
:
@Html.Action("GetCourses", "ControllerName")
或者
@{ Html.RenderAction("GetCourses", "ControllerName"); }
有关缓存的更多信息:使用输出缓存提高性能