2010-11-04 97 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