如何将模型加载到_Layout.cshtml和各种意见之间共享呢? [英] How to load a Model into _Layout.cshtml and share it among various Views?

查看:207
本文介绍了如何将模型加载到_Layout.cshtml和各种意见之间共享呢?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我有一个MVC4项目以两课的交易。整个应用程序的许多页面需要处理课程的列表 - 用户配置文件需要拉起列表中,/课程索引视图需要拉列表等。

I have an MVC4 project that deals with "Courses". Many pages throughout the app need to deal with a list of Courses - user profiles need to pull up the list, the Index view for /Courses needs to pull the list, etc.

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

Since this data is pretty much always required, I'd like to load it as part of the initial request, so I only have to query the DB one time.

我想在这里得到的数据放置在Layout.cshtml,然后其他视图可以根据需要访问模型数据,虽然我没有看到实现这一目标的一条明路的情况。我想我可以把问题分解成两部分:

I imagine a scenario where the data gets placed in Layout.cshtml, and then other views can access the Model data as needed, though I don't see a clear way of achieving this. I think I can break the problem into two pieces:


  1. 获取加载到Layout.cshtml数据

  2. 访问其他意见这个数据

我有点憋屈都 - 我怎样才能使这项工作?

I'm a bit stuck on both - how can I make this work?

推荐答案

您应该使用缓存的OutputCache ,把这个列表到部分查看,然后渲染它无处不在,你需要:

You should use Cache or OutputCache, put this list into a Partial View, and then render it everywhere you need:

1)创建一个动作来pupulate的部分查看。这种观点将被缓存的最大持续时间,那么任何访问不会产生任何开销:

1) Create an Action to pupulate the Partial View. This view will be cached for max duration time, then any access will not generate 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)使用 Chache 填充以同样的方式在部分查看

[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)渲染这个视图由 Html.Action Html.RenderAction

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

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

有关缓存

更多信息:<一href=\"http://www.asp.net/mvc/tutorials/older-versions/controllers-and-routing/improving-performance-with-output-caching-cs\">Improving性能输出缓存

这篇关于如何将模型加载到_Layout.cshtml和各种意见之间共享呢?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆