233
votes

I'm trying to figure out the proper Razor syntax to get a JavaScript file for a particular *.cshtml to be in the head tag along with all the other include files that are defined in _Layout.cshtml.

1
You should also consider putting the js at the bottom of the page instead of in the head section.Mattias Jakobsson
Only issue I found with the sample code is that the @section "JavaScript" need not be enclosed in quotes.Stephen Patten
One more thing: if this is a JavaScript tag, be careful about the usage, I needed to use the END Tag of the script element to get this to run correctly. <script type="text/javascript" src="@Url.Content("~/Scripts/RDA.js")"></script>;Stephen Patten
@Mattias Jakobsson - Not always. That depends on a specific case.Dimskiy
@Dimskiy if you'll allow me to be a word parser and pedant, you should indeed always CONSIDER putting the js at the bottom, whether you actually place it there or not.MrBoJangles

1 Answers

403
votes

You can use Named Sections.

_Layout.cshtml

<head>
    <script type="text/javascript" src="@Url.Content("/Scripts/jquery-1.6.2.min.js")"></script>
    @RenderSection("JavaScript", required: false)
</head>

_SomeView.cshtml

@section JavaScript
{
   <script type="text/javascript" src="@Url.Content("/Scripts/SomeScript.js")"></script>
   <script type="text/javascript" src="@Url.Content("/Scripts/AnotherScript.js")"></script>
}