21
NovDifferent Ways of Rendering Layouts in Asp.Net MVC
Layouts in Asp.Net MVC: An Overview
In Asp.Net MVC, Layouts are like Master Pages in Asp.Net WebForms. These help us maintain a consistent look and feel across all the views within your Asp.Net MVC application. Like Master Pages, layouts may contain common CSS, and jQuery files across the multiple Views and one or more placeholders for which Views provide content. Before it, you can go through types of Layouts like Layouts, RenderBody, RenderSection, and RenderPage in ASP.NET MVC.
In Asp.Net MVC, at the application level, we have a _ViewStart file within the Views folder for defining the default Layout page for your Asp.Net MVC application. In this article, I am going to expose the different ways to apply layout pages for your application. Suppose we have to render the layouts as shown in the fig. by using various ways.
Read More: MVC Interview Questions and Answers
Methods To Render Layouts in Asp.Net MVC
1. Control Layouts Rendering by using the _ViewStart file in the root directory of the Views folder
We can change the default rendering of layouts within the _ViewStart file by using the below code:
@{
var controller = HttpContext.Current.Request.RequestContext.RouteData.Values["Controller"].ToString();
string layout = "";
if (controller == "Admin")
{
layout = "~/Views/Shared/_AdminLayout.cshtml";
}
else
{
layout = "~/Views/Shared/_Layout.cshtml";
}
Layout = layout;
}
2. Return Layout from ActionResult
We can also override the default layout rendering by returning the layout from the ActionResult by using the below code:
public ActionResult Index()
{
RegisterModel model = new RegisterModel();
//TO DO:
return View("Index", "_AdminLayout", model);
}
3. Define the Layout Within Each View on the Top
We can also override the default layout rendering by defining the layout on the view by using the below code:
@{
Layout = "~/Views/Shared/_AdminLayout.cshtml";
}
4. Adding _ViewStart file in each of the Directories
We can also set the default layout for a particular directory by putting the _ViewStart file in each of the directories with the required Layout information as shown below:
@{
Layout = "~/Views/Shared/_AdminLayout.cshtml";
}
Rendering Methods
Method | Description |
RenderBody() | Renders the portion of the child view that is not within a named section. The layout view must include the RenderBody() method. |
RenderSection(string name) | Renders the content of the named section and specifies whether the section is required. |
Summary
I hope you will enjoy the tips while rendering layouts in your MVC application. I would like to have feedback from my blog readers. Your valuable feedback, questions, or comments about this article are always welcome.