ASP.NET MVC緩存使用

 

局部緩存(Partial Page)

1.新建局部緩存控制器:html

    public class PartialCacheController : Controller
    {
        // GET: /PartialCache/
        [OutputCache(Duration = 5)] //緩存5秒
        public ActionResult Index()
        {
            ViewBag.Time = DateTime.Now;
            return PartialView(); //這裏返回的是分部視圖
        }
    }

本想將緩存配置放到配置文件裏面,但報錯了:web

        [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>

運行報錯:spa

這是個Bug問題,.net

解決方法參考:csdn123.com/html/itweb/20130906/104315_104295_104338.htm3d

 感受比較麻煩,分部視圖緩存仍是就用普通方式吧,實在須要在按上面的來處理吧。code

 

2.新建分部視圖:右擊Index,勾選建立爲分部視圖:htm

視圖內容:blog

<p>@ViewBag.Time</p>

3.在須要加載此分部視圖的主視圖頁面添加該分部視圖:get

@{
    ViewBag.Title = "Index";
    Layout = "~/Views/Shared/_Layout.cshtml";
}

<h2>Index</h2>

@Html.Action("Index", "PartialCache")

 

效果:

 

參考來源:

MVC緩存的使用

 

擴展閱讀:

MVC3緩存(一):頁面緩存

MVC3緩存(二): 頁面局部緩存

ASP.NET MVC3緩存之一:使用頁面緩存

相關文章
相關標籤/搜索