Re-Rendering and Re-Compiling are very very different in ASP.Net MVC. While most of the answers here are correct, the View is only compiled once (except in debug mode, where it's compiled each time so you can change the view, hit refresh and see the change, or if the timestamp changes on the file in production). It is compiled into a runtime class that derives from WebViewpage
(no ViewModel) or WebViewPage<T>
(has ViewModel of type T).
The class is instantiated for each view needed (so if you used the same partial multiple times, you have to instantiate the each time), the model is populated, and the execute() method is called to create/stream the HTML to the client. The view could never be cached per model as it is to complicated to do that and instead the MVC team chose to allow configuring caching per controller method, not per WebViewPage.
@ErikPhilips, thanks a lot for this - So the View is only compiled once (no matter if we use or not use OutputCache)? It's the execute method which renders the runtime class into HtmlString, and it is the rendering which would benefit from caching?
Sorta of, but it's much more advanced, easier and complicated then that.
Advanced - The output cache is based on the controller method. So if the output cache configuration determines that the call can use a cached version, the controller method is never called. That's where the huge performance gain is. Imagine no call to the DB / external API call, there isn't a need. You could configure the cache so if it sees id=1
cache it for 30 minutes. Now anyone who calls that method with authorization and id=1
gets the cached string/html.
Easier - You put your OuputCacheAttribute
on a method, configure it and you're done. Pretty darn easy to configure.
Complicated - Caching can be more complicated because you can render other controller methods using Html.Action()
(Html.Partial()
if you don't need a layout for your partial) or the preferred Html.RenderAction();
(Html.RenderPartial()
if you don't need a layout). There use to be a Donut Hole Caching Issue (recommended reading) but that's been fixed for a long time.
execute()
method is called to create/stream the HTML to the client. The view could never be cached per model as it is to complicated to do that and instead the MVC team chose to allow configuring caching per controller method. – Botchy