Search code examples
javascriptasp.net-mvcincluderazorasp.net-mvc-3

ASP.NET MVC 3 Razor: Include JavaScript file in the head tag


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.


Solution

  • 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>
    }