Nikita
Nikita

Reputation: 325

ASP.NET MVC layout

I have layout page and the page that uses layout. How can I add some new elements to the head not changing layout.(layout already contains head)?

Layout:

<head>...</head>

I want my page be like:

<head>all layout head logic... plus
     my page new elements...
     </head>

Upvotes: 2

Views: 346

Answers (1)

Darin Dimitrov
Darin Dimitrov

Reputation: 1038710

You could use sections in the layout. For example:

<html>
<head>
    @RenderSection("scripts", false)
</head>
<body>
    @RenderBody()
</body>
</html>

and then in the view override this section and provide contents for it:

@section scripts {
    <script type="text/javascript">
        alert('hello');
    </script>
}

<div>Hello from the index view</div>

And since the section is optional (second argument = false) if a view doesn't provide any contents for it, it will stay empty.

Upvotes: 3

Related Questions