Write to the head, but not through _Layout.cshtml

I would like to write the head head HTML element independently through the page view, and not through _Layout.cshtml, since each page will require different scripts, metadata, titles, etc. Can this be done in ASP.NET MVC 3, with C # / Razor?

@using Test.Models; @model IEnumerable<Player> <!-- Put JavaScript, CSS etc... Into the page <head> here. --> <h2>Index</h2> <table id="scores"> <tr> <th>Name</th> <th>Age</th> <th>Gender</th> </tr> @foreach(Player p in Model) { <tr> <td>@p.name</td> <td>@p.age</td> <td>@p.gender</td> </tr> } </table> <canvas id="game" width="800" height="600"> <p>Download a modern browser.</p> </canvas> 
+7
source share
3 answers

You can do this using sections. Go to your _Layout.cshtml and add a new section called head as follows:

 <head> <meta charset="utf-8" /> <title>@ViewBag.Title</title> <link href="@Url.Content("~/Content/Site.css")" rel="stylesheet" type="text/css" /> @RenderSection("head", false) </head> 

A new section is added using @RenderSection. Now in your individual views, you can add content to your head as follows:

 @section head { <script type="text/javascript""> //Your java script here </script> } 

When the full view is displayed, javascript will be displayed in the chapter section just below the link tag. You can put something there. For example, meta tags.

+15
source
 var newHeadElement = createSomeElementOrString; document.getElementsByTag("head")[0].appendChild(newHeadElement); 
0
source

Have you tried using razor sections ?

0
source

All Articles