Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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

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?

like image 271
Brendan Vogt Avatar asked Feb 26 '23 14:02

Brendan Vogt


2 Answers

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>
}
like image 155
Esteban Avatar answered Mar 16 '23 22:03

Esteban


I would use @RenderSection("head", false) in my _layout page. Then you can inject whatever you want in the head of the page (including script)...and by using false you make it optional on all of your view pages.

like image 21
Ryan Eastabrook Avatar answered Mar 16 '23 23:03

Ryan Eastabrook