ASP.NET MVC缓存使用
局部缓存(Partial Page)
1.新建局部缓存控制器:
public class PartialCacheController : Controller { // GET: /PartialCache/ [OutputCache(Duration = 5)] //缓存5秒 public ActionResult Index() { ViewBag.Time = DateTime.Now; return PartialView(); //这里返回的是分部视图 } }
本想将缓存配置放到配置文件里面,但报错了:
[OutputCache(CacheProfile = "CacheTime")] public ActionResult Index() { ViewBag.Time = DateTime.Now; return PartialView(); }
配置文件system.web节点下:
<caching> <outputCacheSettings> <outputCacheProfiles> <add name="CacheTime" duration="5" varyByParam="none"/> </outputCacheProfiles> </outputCacheSettings> </caching>
运行报错:
这是个Bug问题,
解决方法参考:csdn123.com/html/itweb/20130906/104315_104295_104338.htm
感觉比较麻烦,分部视图缓存还是就用普通方式吧,实在需要在按上面的来处理吧。
2.新建分部视图:右击Index,勾选创建为分部视图:
视图内容:
<p>@ViewBag.Time</p>
3.在需要加载此分部视图的主视图页面添加该分部视图:
@{ ViewBag.Title = "Index"; Layout = "~/Views/Shared/_Layout.cshtml"; } <h2>Index</h2> @Html.Action("Index", "PartialCache")
效果:
参考来源:
扩展阅读: