ASP.NET MVC: place JavaScript from a View inside the head-section by using sections

When working with ASP.NET MVC, you often need some JavaScript in your views.
The most obvious way of doing this is just adding the JavaScript inside the view:

@{
     ViewBag.Title = "About Us";
 }

<script type="text/javascript">
     // some code
   </script>

<h2>About</h2>
 <p>
      Put content here.
 </p>

Your html source code will end up with a mess:

<!DOCTYPE html>
<html>
 <head>
<meta charset="utf-8" />
<title>About Us</title>
<link href="/Content/Site.css" rel="stylesheet" type="text/css" />
<script src="/Scripts/jquery-1.5.1.min.js" type="text/javascript"></script>
<script src="/Scripts/modernizr-1.7.min.js" type="text/javascript"></script>
</head>
 <body>
     <div>
         <header>
             <div id="title">
                 <h1>Title</h1>
             </div>
            <div id="logindisplay">
                     [ <a href="/Account/LogOn">Log On</a> ]
            </div>
             <nav>
                 <ul id="menu">
                     <li><a href="/">Home</a></li>
                     <li><a href="/Product">Products</a></li>
                     <li><a href="/Home/About">About</a></li>
                 </ul>
             </nav>
         </header>
         <section id="main">
<script type="text/javascript">
            // some code
          </script>
          <h2>About</h2>
          <p>      Put content here. </p>
</section>
        <footer>
        </footer>
     </div>
 </body>
 </html>

As you can see in the code above, the JavaScript was added where the your view was rendered.
To keep your code clean, you can use and render sections!

Open your master View _Layout.cshtml and add a RenderSection:

<!DOCTYPE html>
 <html>
 <head>
     <meta charset="utf-8" />
     <title>@ViewBag.Title</title>
     <link href="@Url.Content("~/Content/Site.css")" rel="stylesheet" type="text/css" />
     <script src="@Url.Content("~/Scripts/jquery-1.5.1.min.js")" type="text/javascript"></script>
     <script src="@Url.Content("~/Scripts/modernizr-1.7.min.js")" type="text/javascript"></script>
     @if (IsSectionDefined("MyOtherJavascript"))
     {
       @RenderSection("MyOtherJavascript");
     }
 </head>
 <body>

Now in your View (in my case /Home/About.cshtml) add the section:

@{
     ViewBag.Title = "About Us";
 }
@section MyOtherJavascript {
   <script type="text/javascript">
     // some code
   </script>
 }
<h2>About</h2>
 <p>
      Put content here.
 </p>

Now your JavaScript will be injected inside the header:

<!DOCTYPE html>
 <html>
 <head>
     <meta charset="utf-8" />
     <title>About Us</title>
     <link href="/Content/Site.css" rel="stylesheet" type="text/css" />
     <script src="/Scripts/jquery-1.5.1.min.js" type="text/javascript"></script>
     <script src="/Scripts/modernizr-1.7.min.js" type="text/javascript"></script>
<script type="text/javascript">
     // some code
   </script>
 </head>
 <body>
<!-- ... -->

That’s it! :)
You can add more logic to it, there is also an overload of the RenderSection in case you just want to say it is optional or not.

I demonstrated the RenderSection by injecting JavaScript into the header, but this can be used in other places (and you can also inject and render normal html code). ;-)

FYI: I’m using ASP.NET MVC 3 with Razor engine.

msdn ]

About these ads

8 thoughts on “ASP.NET MVC: place JavaScript from a View inside the head-section by using sections

    • Hmm Shawn, what is the reason for it? I’ve always seen it at the top instead of the bottom. I’m curious.. Is it just because of the loading/rendering times?

  1. @getsometoast – Performance is only 1 reason to put the javascript at the bottom of the page. Another is for SEO purposes. While jQuery document ready doesn’t fire until the page is loaded, it still makes sense semantically to put the script at the bottom of the page. I usually use Yahoo.Yui.Compressor to minify it, too.

  2. I have example like you, but I render some partial view and inside partial view I have section part with javascript code. This section with javascript doesn’t render. Why?

  3. Ivory usually came from Nile hippos and were used for carving combs and jewelry.. The consequence seemed to b a departure coming from Monclers serioussports custommoncler doudoune a very goo update. [url=http://www.ecotrucastuces.fr/canada-goose-freestyle-vest-blanc-homme-boutique.html]Canada Goose Freestyle Vest Blanc Homme boutique[/url] Defovu [url=http://www.torfisk.dk/cg_dk/]canada goose udsalg[/url]
    [url=http://www.torfisk.dk/cg_dk/index.asp?id=99]canada goose pris[/url] Mymxhh Monogram canvas is the main material that they use in manufacturing these handbags. [url=http://www.buckshotbooks.ca/2013/11/canada-goose-youth-jacket/]canada goose youth jacket[/url]
    [url=http://www.creasite84.fr/canada-goose-camp-down-hooded-jacket-c-39_51/canada-goose-camp-down-hooded-blanc-solde-p-178.html]Canada Goose Camp Down Hooded Blanc soldé[/url] 8374013058 [url=http://www.1625wontpass.ca/2013/11/03/canada-goose-banff-parka-black-sale/]canada goose banff parka black sale[/url]

Leave a Reply

Fill in your details below or click an icon to log in:

WordPress.com Logo

You are commenting using your WordPress.com account. Log Out / Change )

Twitter picture

You are commenting using your Twitter account. Log Out / Change )

Facebook photo

You are commenting using your Facebook account. Log Out / Change )

Google+ photo

You are commenting using your Google+ account. Log Out / Change )

Connecting to %s