Tuesday, July 30, 2013

Nested Layout pages in ASP.NET MVC

Like nested master page in ASP.NET, we can use nested layout pages in ASP.NET MVC. A layout page is a typical HTML page with a special @RenderBody() section. Here is a simple example of layout page:

<!DOCTYPE html>

<html >

<head>

    @RenderSection("styles", required: false)

</head>

<body>

    @RenderBody()

    @RenderSection("scripts", required: false)

</body>

</html> 

We can optionally define “name sections”. In the above layout page, we have define two optional name sections. Now let’s define a inner layout page:

@{

Layout = "~/Views/Shared/_Layout.cshtml";

}

@section styles {

<link href="~/Areas/Second/Content/aStyle.css" rel="stylesheet" />

}

@RenderBody()

In the above layout page, we are referring parent layout page. This inner layout page has to have a render body section. The name section is optional. You can use any of the parent name sections.

Now, we can use this nested layout page into any view.

Hope this helps!

No comments: