CD..
CD..

Reputation: 74126

ASP.NET MVC saving a rendered view to html

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?

Upvotes: 1

Views: 4489

Answers (3)

CD..
CD..

Reputation: 74126

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?

Upvotes: 2

Cyril Gupta
Cyril Gupta

Reputation: 13723

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");
    }
}

Upvotes: 0

maciejkow
maciejkow

Reputation: 6453

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

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

Upvotes: 5

Related Questions