Place JavaScript Code Inside Head Tag in ASP.NET MVC 2 and MVC 3


To properly place JavaScript inside <head> tag in ASP.NET MVC 2, I just need to add ContentPlaceHolder control as my place holder for all JavaScript code from individual pages. So, in my Site.Master page, I have:

<head runat="server">
    <title><asp:ContentPlaceHolder ID="TitleContent" runat="server" /></title>
    <link href="../../Content/Site.css" rel="stylesheet" type="text/css" />
    <script language="javascript" type="text/javascript" src="../../Scripts/Js/jquery-1.4.2.min.js"></script>
    <asp:ContentPlaceHolder ID="ScriptContent" runat="server" />

Then, in the view pages that refer to this master page, I can have:

<asp:Content ID="Content2" ContentPlaceHolderID="ScriptContent" runat="server">
    <script language="javascript" type="text/javascript">
        $(function () {});

This way, my JavaScript code will fall inside <head> tag when rendered.


In ASP.NET MVC 3, this technique is still applicable when you use ASPX (C#) view engine. However, it doesn’t when Razor (CSHTML) view engine is used.

To properly place JavaScript code inside <head> tag in ASP.NET MVC 3 with Razor (CSHTML), add the “@RenderSection” inside <head> tag in your “_Layout.cshtml” file. Something like this:

    <link href="@Url.Content("~/Content/Site.css")" rel="stylesheet" type="text/css" />
    <script src="@Url.Content("~/Scripts/jquery-1.4.4.min.js")" type="text/javascript"></script>
    @RenderSection("ScriptTag", false)

Then, in view page, you can just add the following code:

@section ScriptTag
    <script type="text/javascript" language="javascript">
        $(function () {});

What “@RenderSection” gives you is sort of reference point that you can refer to from your view page with “@section” keyword following your section name that you define when you call “@RenderSection”. In this case, “ScriptTag” is my section name.

When the view is rendered, your JavaScript code will be inside <head> tag.

Leave a Reply

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

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

Google photo

You are commenting using your Google 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 )

Connecting to %s