DEV Community

Hòa Nguyễn Coder
Hòa Nguyễn Coder

Posted on

ASP.NET MVC 5 Create Shared Layout Razor & ViewStart

In article, I have shared way create Layout Razor and ViewStart in ASP.NET MVC 5, we can configuration the interface layout for the website

  • Views/Shared: you need create Shared foler in View directory. Shared folder, using display View in multiple Controller, using Configuration the interface for the website You to Views/Shared directory, create new _LayoutPage1.cshtml file and pass the following below code ASP.NET MVC 5 Create Shared Layout Razor & ViewStart
<!DOCTYPE html>

<html>
<head>
    <meta name="viewport" content="width=device-width" />
    <title>@ViewBag.Title</title>
</head>
<body>
    <div>
        @RenderBody()
    </div>
</body>
</html>
Enter fullscreen mode Exit fullscreen mode

The @RenderBody():using display content in multiple controller to View
Example you can fixed (Header/Footed) the interface for the website, only change content in RenderBody(), (header/footer) is not change

<html>
<head>
    <meta name="viewport" content="width=device-width" />
    <title>@ViewBag.Title</title>
</head>
<body>
    <div class="header">
        <!--code header fixed-->
    </div>
    <div>
        @RenderBody()
    </div>
    <div class="footer">
        <!--code footer fixed-->
    </div>
</body>
</html>
Enter fullscreen mode Exit fullscreen mode

So you have fixed the (header/footer) for the website.
Okay, you need using _LayoutPage1.cshtml, so you to Views/Home/index.cshtml opent it, pass the following below code

@{
    ViewBag.Title = "Index";
    Layout = "~/Views/Shared/_LayoutPage1.cshtml";
}
Enter fullscreen mode Exit fullscreen mode

Okay, You are create layout razor success!

  • _ViewStart.cshtml: used to define the layout for the website, you can set the layout settings as well, if HomeController using Layout _LayoutHome.cshtml or AdminController is _LayoutAdmin.cshtml
//Views/ViewStart.cshtml
@{
    Layout = "~/Views/Shared/_LayoutPage1.cshtml";
}
Enter fullscreen mode Exit fullscreen mode

You can configuration _ViewStart.cshtml the following below code:

@{

    string CurrentName = Convert.ToString(HttpContext.Current.Request.RequestContext.RouteData.Values["Controller"]);
    string clayout = "";
    switch (CurrentName)
    {
        case "Home":
            clayout = "~/Views/Shared/_LayoutHome.cshtml";
            break;
        default:
            //Admin layout  
            clayout = "~/Views/Shared/_LayoutAdmin.cshtml";
            break;
    }
    Layout = clayout;

}
Enter fullscreen mode Exit fullscreen mode

ASP.NET MVC 5 Create Shared Layout Razor & ViewStart -  hoanguyenit.com

You can run browser:
http://localhost:49763/Admin/Index or http://localhost:49763/Home/Index

Post:

Top comments (0)