2010-11-04 165 views
9

我目前正在開發一個使用asp.net mvc 2在c#中的網站。我從未在MVC中使用緩存功能,並希望將其應用於用戶個人資料頁面。此頁面上的內容很少發生變化,實時需要的部分是用戶最近發佈的帖子列表。 (我使用linq-to-sql從數據庫加載數據)Asp.net MVC 2緩存

我需要一些關於我應該使用哪種緩存技術以及如何實現它的建議?

更新: Xandy的解決方案几乎可行,但我無法傳入數據。我將如何使用?重寫這個? Html.RenderPartial(「UserPosts」,ViewData [「UserPosts」])

+0

另請參閱http://stackoverflow.com/questions/4082826/when-and-how-to-go-about-performing-caching-in-asp-net-mvc/4091232#4091232 – 2010-11-06 03:27:42

+0

任何人都知道答案?我的更新? – Rana 2010-11-08 21:09:46

+0

您需要使用RenderPartial的第四個重載(http://msdn.microsoft.com/zh-cn/library/dd470561.aspx)嘗試:'Html.RenderPartial(「UserPosts.ascx」,Model.UserPosts,new ViewDataDictionary {Model = Model.UserPosts}'。 – RPM1984 2010-11-09 04:18:59

回答

1
+0

是的,我也看到了,但是如何緩存頁面而不將其緩存呢? – Rana 2010-11-04 02:36:03

+0

接下來討論部分緩存。 http://www.asp.net/mvc/tutorials/adding-dynamic-content-to-a-cached-page-cs – xandy 2010-11-04 03:57:08

+0

這仍然是MVC 2中的首選方法嗎? – Rana 2010-11-04 05:50:24

5

至於其他的答案已經指出,甜甜圈緩存「之類的」在MVC作品緩存。

我不會推薦它 - 相反,我會提供一個alterantive:

你必須爲用戶帶來查看資料,讓我們把它稱爲「UserProfile.aspx」。

現在在這個視圖中,你有一堆HTML,包括「最近的帖子」部分。

現在,我假設這是類似於最後10個帖子爲用戶

我會做的就是把這個HTML /段劃分爲局部視圖,並通過一個單獨的操作方法爲它服務,也叫做PartialViewResult:

public class UserProfileController 
{ 
    [HttpGet] 
    [OutputCache (Duration=60)] 
    public ActionResult Index() // core user details 
    { 
     var userProfileModel = somewhere.GetSomething(); 
     return View(userProfileModel); 
    } 

    [HttpGet] 
    public PartialViewResult DisplayRecentPosts(User user) 
    { 
     var recentPosts = somewhere.GetRecentPosts(user); 
     return PartialViewResult(recentPosts); 
    } 
} 

使用呈現出局部視圖的jQuery:

<script type="text/javascript"> 
    $(function() { 
    $.get(
     "/User/DisplayRecentPosts", 
     user, // get from the Model binding 
     function (data) { $("#target").html(data) } // target div for partial 
    ); 
    }); 
</script> 

這樣,你可以最大化OutputCache的核心細節(Index()),但最近的帖子沒有被緩存。 (或者你可以有一個非常小的緩存期)。

呈現部分的jQuery方法與RenderPartial不同,因爲這樣您可以直接從控制器提供HTML,因此您可以相應地控制輸出緩存。

最終結果與甜甜圈緩存非常相似(緩存部分頁面,其他部分不緩存)。

+1

那麼沒有JavaScript的客戶端呢? – xandy 2010-11-06 10:13:23

+2

OP是否有這樣的要求? – RPM1984 2010-11-06 11:51:31