Partial Views

Layouts and sections are a powerful and effective technique for creating maintainable websites because they provide the ability to split a given web page into smaller, more focused parts. In addition to layouts and sections, WebMatrix offers yet another compartmentalization technique called partial views, which are self-contained portions of markup that can be reused throughout the website. Partial views are also useful for separating complex or lengthy portions of markup from a page, making them easier to read and understand (and by extension, easier to maintain).

Creating Partial Views

To create a partial view, it is often easiest to start with existing markup from an existing web page. For example, assume that we’d like to create a new page to show the contents of a single blog post, reusing the markup within the foreach loop on the blog’s home page that lists all of the blog posts:

@foreach(var in posts) {
    var url = "http://www.myblog.com/posts/post.cshtml"id=" + post.ID;

    <div>
        <h3>@post.Title</h3>
        <div>@post.Body</div>
        @TwitterHelpers.TweetButton( url: url, text: @post.Title )
        @Facebook.LikeButton( href: url )
    </div>
}

In order to turn the inner contents of the foreach loop into a partial view, you must first create a new Razor file to hold the contents of the new partial view. To do so, right-click on the Posts folder and from the New File dialog, select the CSHTML file type (that’s right, the same file type we’ve been using for full Razor pages and layouts). Name ...

Get Programming Razor now with the O’Reilly learning platform.

O’Reilly members experience books, live events, courses curated by job role, and more from O’Reilly and nearly 200 top publishers.