October 25, 2019 09:18 by
Peter
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.
<!DOCTYPE html>
<html>
<head>
<meta name="viewport" content="width=device-width" />
<title>@ViewBag.Title</title>
</head>
<body>
<div>
@RenderBody()
</div>
</body>
</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.
<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>
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.
@{
ViewBag.Title = "Index";
Layout = "~/Views/Shared/_LayoutPage1.cshtml";
}
_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
//Views/ViewStart.cshtml
@{
Layout = "~/Views/Shared/_LayoutPage1.cshtml";
}
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;
}
This gives you an idea, how to use a Razor layout in various pages.