A View by Any Other Name...

Some of the most common confusions I hear about from MVC developers concern views, specifically layouts vs. partial views vs. views. The simple fact is that the terms "layout" and "partial" merely exist to describe how a view is being utilized. In truth, there is no such thing as a layout or a partial view: there's just "views".

Razor, the view system in MVC, is actually pretty ingenius. It's far more powerful than most MVC developers ever realize, and that power comes from the fact that it's so agnostic. It just processes files with a cshtml or vbhtml extension (depending on your language choice). How it processes them, though, is determined contextually.

A layout, for example, is merely a view that's used as a layout. As Razor is processing the view, it looks to see if either the view sets Layout or if there's an applicable _ViewStart.cshtml that sets Layout. If either of those is true, it loads the view referenced by Layout and dumps the contents of the primary view it's rendering wherever that view calls RenderBody(). That's all there is to it. You could use literally any view as a "layout". It doesn't even need to call RenderBody(); it just wouldn't actually do anything worthwhile if it doesn't. However, it would still "work": you would not get an exception or any other indication that something was wrong.

Similarly, partial views are just views used as partial views. When you either render a partial view within a view using Html.Partial or Html.RenderPartial or return PartialView from an action, Razor merely ignores any value set for Layout and just returns the contents of the partial view.

Handling views this way gives developers ultimate flexibility. The same view can be used as a traditional view or a partial, meaning greater code reuse. Layouts can extend other layouts because they are just views, entitled to reference a layout just like any other view can. It's all just "views".

comments powered by Disqus