Layouts and Partial Views in Razor

Razor allows the most maintainable view engine available with numerous sophisticated tools to define site layout, sub navigation and even the rendering of specific sub-items inside of a page. It allows you to set individual parameters including the ability to map parameters to areas of the page.

Layouts

Razor layouts are analogous to the familiar ASPX master page. They allow you to define elements you want to be common across your site and define the regions of a page that you want specific views to render.

Razor gives you a lot more control in what is sent from the server to the client than classic ASP.NET. Classic ASP.NET included viewstate and multiple standard Microsoft supplied JavaScript libraries. Users of ASP.NET Ajax added several more mandatory Microsoft supplied JavaScript libraries. The result was a basic starter ASP.NET page that had about six to eight external resources that had to be loaded.

Microsoft recognized this as an opportunity to update the server-side portions of their framework to be cross-compatible with popular JavaScript libraries such as jQuery so developers could leverage all of the great server-side capabilities provided by Microsoft without adding to the download weight on the client. Razor even helpfully includes jQuery in its default Scripts folder.

Layouts can be specified manually CSHTML file or they can be set implicitly by your _ViewStart.cshtml files. To set it manually, set the Layout property at the top of your view as seen in the following code block.

@{
Layout = "~/Shared/_Layout.cshtml";
ViewBag.Title = "This is my page title.";
}

Using _ViewStart.cshtml

You can also specify layouts implicitly by using _ViewStart.cshtml files. These files have the advantage of applying themselves in an inheritable fashion to all of your views. This means that instead of setting the layout of your specific views by setting a property in the header, you can do it in a way that cross-cuts your files. Likewise you can include common code you want run on all page views within a specified scope.

When you create a new ASP.NET MVC3 Razor site, it will include a _ViewStart.cshtml file in the Shared folder. This file will be run on all view pages across your entire MVC3 site unless there is a more specific _ViewStart.cshtml file in scope on one of your other views. The code block below shows the default content of this file, which calls out the specific layout that should be applied by default. In this case it is the _Layout.cshtml file defined in the /Shared folder. You can either customize the _Layout.cshtml file to apply your site layout to your entire site or you can define a new layout and specify that layout in the _ViewStart.cshtml file.

@{
Layout = "~/Views/Shared/_Layout.cshtml";
}

Although the most common use for customizing the _ViewStart.cshtml file is to define the layout you want applied across your pages, you can also define code blocks here that do anything you want.

If you define another _ViewStart.cshtml file inside of a more specific directory than the shared folder, then that _ViewStart.cshtml file will be called after your universal one. Since it is called after your universal file, the properties set in your more specific file will override the universal one allowing you to choose different layouts for specific directories.

Building a Layout

The layout files themselves are mainly HTML with a few special Razor commands thrown in. The @ViewBag.Title contains the page's title being rendered. The @RenderBody() function renders the body of the view the layout is being applied to.

In addition to the RenderBody() function, which renders the view inside of the layout, you can define as many named sections as you need using the @RenderSection() function. This function's arguments are a string name of the section and a Boolean indicating whether or not the view page must define this section or if it is optional.

@RenderSection("TestSection",false)

In your view page, to render the specified section declare, use the @section SectionName syntax to declare your section block.

@section TestSection
{
This is my test section.
}

You can define your sections in conditional blocks in your layout page. For example, if you wanted to only show a particular section if a user has a valid login, you could define that section inside of a conditional and it won't break your view page.

If you want to define default section content to be displayed when your view doesn't define a given section, you can use the IsSectionDefined function to test whether or not your view page defines that section.

@if (IsSectionDefined("TestSection"))
{
@RenderSection("TestSection", false)
}
else
{
<div>The view didn't define the TestSection</div>
}

Partial Views

Partial views in MVC3/Razor allow you to define common shared parts of a page that can be leveraged by multiple pages in your site. To define a partial view, add a method to your controller that returns PartialViewResult to your controller.

public PartialViewResult ViewName()
{
return new PartialViewResult();
}

Once you have defined the method in your controller, you can right click the method name and choose "Add View". In the dialog that appears, make sure you check the Partial View checkbox. Visual Studio.NET 2010 will generate a blank .cshtml for you to define your partial view in.

To call your partial view from your view page, use the @Html.Partial("ViewName") helper function. You can also optionally pass in a model or leave it blank for the current view data to be passed in.

Conclusion

Razor layouts are inheritable and scoped allowing you great flexibility in making site wide changes to your ASP.NET MVC 3 web application. You can also specify layouts to use on a given view and render partial views to provide user interface layer code reuse.

Razor allows the most maintainable view engine available with numerous sophisticated tools to define site layout, sub navigation and even the rendering of specific sub-items inside of a page. It allows you to set individual including the ability to map parameters to areas of the page.

About the Author

David Talbot has over 14 years of experience in the software industry with experience ranging from license plate recognition using neural networks to television set-top boxes to highly scalable web applications. His main focus is building rich user interface web applications on the .NET platform. He is also the author of Applied ADO.NET and numerous articles on technology.



Related Articles

Comments

  • Discount Oakley Straight Jacket online store

    Posted by fxfjbhorg on 07/08/2013 04:31pm

    Discount Oakley Sunglasses ,Oakley is a technique crystallization of high-tech and intelligent, creating a compilation of high-performance fashion eyewear. These sunglasses within a different lens color and tone, almost each and every last style continues to be put together by expert designers to make the wearer ugly fashion, taste and fashion. It is certainly one of Oakley science, but a science and art combine to produce some of the best on this planet Engineering sunglasses. Fake Oakley Oil Rig ,One example could possibly be interpreted to the classic type of romantic named Oakley Romeo and Juliet "sunglasses. If you want to pick a better view, to offset the Oakley sunglasses in the open and clear. Although Oakley sunglasses optical brand choice, we recommend the label of Oakley sunglasses. The structure inspiration for Oakley, Oakley LIVESTRONG exclusive edition sunglasses from U.S. Mlb official glasses to help you make your mind more mysterious. One of several criteria considered in the recovery cup would be to be sure that a duplicate of the Kun pounds acuity, another may meet your visual taste. cheap oakley sunglasses ,If you possess OAKLEY sunglasses meters framework to look at good thing about these guys around the beach or skiing, to strengthen all HLS is usually a real ice section, you could end up the real difference of any two small brown eyes, browse them. Oakley sunglasses has to be option to suit your needs. Holbrooke Oakley sunglasses manufactured many different frame. This makes the wearer's temples, and also to adjust to different shapes and forms, so comfortable. Fake ray bans ,Oakley Frogskins sunglasses sunglasses good reputation for probably the most well-known style. It is a new trend now online buy discount Oakley sunglasses. Oakley sunglasses have been revolutionary design and suspension system framework that it will not affect the camera lens. Sac Longchamp Pliage Cheval Au G ,Women may decide to glance a few very eye-catching in the general population, women cheap Oakley women's sunglasses to substantiate the purchase in the U.S. flag. If you live in the nearby California or if you have regular planned activity, you must concentrate on these materials, these kinds of sunglasses are created which are more secure, real relaxed. Retailers advertised a variety of designer sunglasses, they are not just the overall goal is usually to supply the framework of fashion, nevertheless they give you the greatest level of eye protection sunglasses glasses stock.

    Reply
  • Abercrombie And Fitch

    Posted by gogodjh on 05/14/2013 08:04pm

    I like the helpful information you provide in your content articles. I’ll bookmark your weblog and check again here frequently. I am quite certain I will learn lots of new stuff in this article! Good luck for the next! oakley sunglasses sale oakley sunglasses canada toms shoes

    Reply
  • MVC Partial View

    Posted by Naresh on 05/22/2012 02:25am

    Hi, I have a .cshtml page i want load it into Layout.cshtml as user control in classic asp.net. Could you please help me. how to do.

    Reply
  • MVC Still Requires Several External Resources

    Posted by TexasJetter on 03/28/2011 04:42pm

    " Classic ASP.NET included viewstate and multiple standard Microsoft supplied JavaScript libraries. Users of ASP.NET Ajax added several more mandatory Microsoft supplied JavaScript libraries. The result was a basic starter ASP.NET page that had about six to eight external resources that had to be loaded." While the Viewstate is gone (thank goodness) there are still several external JavaScript libraries that MVC includes. You have jQuery, jQuery.Validate, MicrosoftMvcValidation. If using Ajax you have MicrosoftAjax and MicrosofMvcAjax. Razor adds a new jQuery.Unobtrusive-ajax as well. And if you want to use jQuery Ui for date pickers,widgets, autocompletes, etc. you have it to load as well. MVC has a lot of good things going for it, but I donbt see reducing external resources (other than viewstate) as one of them.

    • Optionally, yes

      Posted by DavidTalbot on 03/29/2011 12:04pm

      From the author: In MVC all of those scripts you mention are OPTIONAL. 1) I can create a page in MVC3 that returns just "Hello World" to the browser with no additional scripts. 2) When you do choose to use the scripts microsoft provides in MVC3, the total size is substantially less than it was in MVC2 to accomplish the same ends. Add to that MVC3 allows you to use jquery, a library pretty much every modern web app is using already, saves you even more.

      Reply
    Reply
Leave a Comment
  • Your email address will not be published. All fields are required.

Top White Papers and Webcasts

  • On-demand Event Event Date: October 29, 2014 It's well understood how critical version control is for code. However, its importance to DevOps isn't always recognized. The 2014 DevOps Survey of Practice shows that one of the key predictors of DevOps success is putting all production environment artifacts into version control. In this webcast, Gene Kim discusses these survey findings and shares woeful tales of artifact management gone wrong! Gene also shares examples of how high-performing DevOps …

  • On-demand Event Event Date: December 18, 2014 The Internet of Things (IoT) incorporates physical devices into business processes using predictive analytics. While it relies heavily on existing Internet technologies, it differs by including physical devices, specialized protocols, physical analytics, and a unique partner network. To capture the real business value of IoT, the industry must move beyond customized projects to general patterns and platforms. Check out this webcast and join industry experts as …

Most Popular Programming Stories

More for Developers

RSS Feeds