ASP.NET MVC 5 Create Shared Razor Layout And ViewStart

In this blog you will learn about ASP.NET MVC 5 Create Shared Razor Layout & ViewStart.

In article, I have shared a way to create a Layout Razor and ViewStart in ASP.NET MVC 5.
 

Views/Shared

 
You need to create a shared folder, "Shared" in the Views directory.
 
Go Views/Shared directory and create new _LayoutPage1.cshtml file and write the following below code. 
 
  1. <!DOCTYPE html>  
  2.   
  3. <html>  
  4. <head>  
  5.     <meta name="viewport" content="width=device-width" />  
  6.     <title>@ViewBag.Title</title>  
  7. </head>  
  8. <body>  
  9.     <div>  
  10.         @RenderBody()  
  11.     </div>  
  12. </body>  
  13. </html>  
The @RenderBody()
 
Use display content in multiple controllers to View.

Example you can have a fixed header and footer in the page. Only change will be the content of the RenderBody() called in the code.
  1. <html>  
  2. <head>  
  3.     <meta name="viewport" content="width=device-width" />  
  4.     <title>@ViewBag.Title</title>  
  5. </head>  
  6. <body>  
  7.     <div class="header">  
  8.         <!--code header fixed-->  
  9.     </div>  
  10.     <div>  
  11.         @RenderBody()  
  12.     </div>  
  13.     <div class="footer">  
  14.         <!--code footer fixed-->  
  15.     </div>  
  16. </body>  
  17. </html>  
So you have fixed the (header/footer) for the website.
 
Okay, you need using _LayoutPage1.cshtml, so you to Views/Home/index.cshtml. Open it, pass the following below code.
  1. @{  
  2.     ViewBag.Title = "Index";  
  3.     Layout = "~/Views/Shared/_LayoutPage1.cshtml";  
  4. }  
_ViewStart.cshtml used to define the layout for the website. You can set the layout settings as well, if HomeController is using Layout.
 
_LayoutHome.cshtml or AdminController is _LayoutAdmin.cshtml
  1. //Views/ViewStart.cshtml  
  2. @{  
  3.     Layout = "~/Views/Shared/_LayoutPage1.cshtml";  
  4. }  
You can configuration _ViewStart.cshtml the following below code.
  1. @{  
  2.   
  3.     string CurrentName = Convert.ToString(HttpContext.Current.Request.RequestContext.RouteData.Values["Controller"]);  
  4.     string clayout = "";  
  5.     switch (CurrentName)  
  6.     {  
  7.         case "Home":  
  8.             clayout = "~/Views/Shared/_LayoutHome.cshtml";  
  9.             break;  
  10.         default:  
  11.             //Admin layout    
  12.             clayout = "~/Views/Shared/_LayoutAdmin.cshtml";  
  13.             break;  
  14.     }  
  15.     Layout = clayout;  
  16.   
  17. }  
This gives you an idea, how to use a Razor layout in various pages. 
 
 
The previous article,