Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Writing to head, but not via _Layout.cshtml

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>
like image 648
Jack Avatar asked Jan 20 '12 19:01

Jack


1 Answers

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.

like image 107
Kevin Junghans Avatar answered Sep 23 '22 16:09

Kevin Junghans