Thursday, February 13, 2014

ASP.NET MVC5 (Novice) Creating different layouts for different views

I’m creating a simple login-protected site. I want to have a main layout for the core site and a separate layout for the login and other account-related pages.

 

It took me a while to stumble on the most ‘elegant’ answer for ASP.NET MVC 5. The easiest/best solution (also restated here) is to copy _ViewStart.cshtml from the View folder root to the view folder that you want to style differently.

 

Create a new layout in ~/Views/Shared … (_Layout-Account.cshtml in my case)

 

and edit ~/Views/Account/_ViewStart.cshtml to point to the new Layout.

 

This will override the main _ViewStart.cshtml in the Views folder. There are many other approaches, like adding conditional logic to the main _ViewStart.cshtml page, but creating a _ViewStart.cshtml page for each view you

 

Shailendra Chauhan made an excellent blog post exploring many different ways of rendering layouts in ASP.NET MVC.

1 comment:

  1. Hi Brien. I read your article and I have a question. Lets say you have ten different views apart from the Account view with the same layout and you wanted to change something in one of them, wouldn't you have to change it in all the other views separately to effect the change you want?

    ReplyDelete