Asp.net MVC 2 caching

前端 未结 3 2036
星月不相逢
星月不相逢 2021-02-04 14:14

I\'m currently developing a web site using asp.net mvc 2 in c#. I have never used the caching feature in MVC and would like to apply it to the user profile page. The content on

相关标签:
3条回答
  • 2021-02-04 14:42

    ASP.Net has a tutorial on output caching for MVC.

    Partial (aka Donut) Caching which would work for MVC2.

    0 讨论(0)
  • 2021-02-04 14:53

    Phil Hack's fragment caching tricks no longer work in MVC2.

    At StackOverflow we build html fragments as text and cache them using HttpRuntime.Cache and more.

    0 讨论(0)
  • 2021-02-04 14:55

    As other answers have stated, donut caching "sort of" works in MVC.

    I wouldn't recommend it - instead i'll offer an alterantive:

    You have a View for the Users Profile, let's call it "UserProfile.aspx".

    Now on this View, you have a bunch of HTML, including a section for "recent posts".

    Now, i am assuming this is something like the last 10 posts for the user.

    What i would do is put this HTML/section into a Partial View, and serve it via a seperate action method, aka a 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);
       }
    }
    

    Render out the Partial View using 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>
    

    That way, you can max out the OutputCache for the core details (Index()), but the recent posts are not cached. (or you can have a very small cache period).

    The jQuery method of rendering the partial is different to RenderPartial, as this way you are serving the HTML directly from the controller, so you can control the output caching accordingly.

    The end result is very similar to donut caching (parts of the page cached, other's not).

    0 讨论(0)
提交回复
热议问题