tags:

views:

162

answers:

3

Hi All,

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?

+4  A: 

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

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

maciejkow
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
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
A: 

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
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
A: 

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?

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