1

I'd like to have an action that on the first request will save the view result to a HTML file and then return the view, and in the next request the MvcHandler will just point to this generated HTML file without referring to the controller, this way I can avoid some heavy DB work in pages that usually stay static.

How can this be done?

CD..
  • 72,281
  • 25
  • 154
  • 163

3 Answers3

5

You don't have to. Just use OutputCache attribute.

See http://www.asp.net/learn/mvc/tutorial-15-cs.aspx

maciejkow
  • 6,403
  • 1
  • 27
  • 26
  • 1. Does this use the file system for caching or is it in memory? 2. I might want to skip the action and move the user to the Html file from the custom MvcHandler if possible, does that make sens? – CD.. Aug 03 '09 at 10:59
  • as far as I know, OutputCache attribute uses asp.net's cache. You can refer to documentation (http://msdn.microsoft.com/en-us/library/xsbfdd8c.aspx) to get anwsers for those questions. – maciejkow Aug 03 '09 at 11:14
2

I found what I was looking for in the answer Dan Atkinson gave for this question:

Rendering a view to a string in MVC, then redirecting — workarounds?

Community
  • 1
  • 1
CD..
  • 72,281
  • 25
  • 154
  • 163
  • Is there a specific reason why OutputCache wouldn't work in this case? I'll be honest with you: If I'm a developer taking over maintenance for this app, I would expect to see some type of standard caching in place -- not some home grown stuff, unless you've got a good reason for it. – Dan Esparza Aug 15 '09 at 22:51
  • The truth is I'm not sure my idea is the best for caching the pages, I suppose you are right. I thought that if the content is static there is no reason to generate the page again and again and I can save some DB work too. are you sure this is a bad approach in any case? – CD.. Aug 15 '09 at 23:07
0

While what you've described is indeed a possible strategy to speed up things, OutputCache is a viable alternative.

The outputcache lives in the memory for a finite time. Also note that if you write a HTML file there will be a write operation involved. You may also need a mechanism to refresh the HTML file you've written.

If you want to stick with your own strategy (read a file from the server) you could do that easily.

In the Controller you could check if your file exists like this.

public ContentResult MyPage()
{
    if(System.IO.File.Exists(Server.MapPath("myFile.html"))
    {
      return Content(System.File.ReadAllText("myFile.html");
    }
    else
    {
         GenerateMyFile(); //This function generates the file
         return Content(System.File.ReadAllText("myFile.html");
    }
}
Cyril Gupta
  • 13,505
  • 11
  • 64
  • 87
  • I'm still not sure what's the best way doing this. but I'd like to test both. My question is really about implementing this GenerateMyFile() method. Any idea? – CD.. Aug 03 '09 at 19:12