I would like to write to the HTML head element independently via the page view, not through the _Layout.cshtml as each page will require different scripts, meta data, 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>
You can do this by using sections. Go to your _Layout.cshtml and add a new section called head like this:
<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>
The new section is added with the @RenderSection. Now in your individual views you can add content to the head like this:
@section head
{
<script type="text/javascript">
//Your java script here
</script>
}
When the complete view is rendered the javascript would be rendered in the head section just below the link tag. You could put anything in there. For example, meta tags.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With