Javascript – ASP.NET MVC 3 How to inject Javascript into the master layout

asp.net-mvc-3javascriptrazor

I am trying out the new razor view engine from MVC 3. The issue that I am having is that I have Javascript that is page specific. I normally have all my Javascript code before the tag closes. I was thinking of putting a section just before I close the body tag on my master layout. Some thing to the effect of:

<script type="text/javascript">
   @RenderSection("JavaScript")
</script>

But VS2010 underlines it in green. So which ever pages uses this master layout can have it's Javascript injected Here. How would you guys do it? The reason why I want to do it like this is because then I can add JavaScript from the master layout also in here, other I will have to define a separate script tag just below the @RenderSection.

When I do the following then VS gives me a warning (I don't like warnings):

Validation (HTML 4.01): Element 'link' cannot be nested within element 'link'.

Here is my code for the above warning:

@section HeadSection
{
    <link href="http://yui.yahooapis.com/2.8.2r1/build/button/assets/skins/sam/button.css" rel="stylesheet" type="text/css">
    <link href="http://yui.yahooapis.com/2.8.2r1/build/datatable/assets/skins/sam/datatable.css" rel="stylesheet" type="text/css">
}

How can I get these warnings away?

Best Answer

Here's what I'd do, according to the best practices you should place your scripts at the bottom of the page.

_Layout.cshtml

<html>
    <head>
        @* ... *@
    </head>
    <body>
        @* ... *@        
        @RenderSection("Scripts", false)
    </body>
</html>

MyView.cshtml

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