RSS

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

14 Mar

ASP.NET MVC 2

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" />
</head>

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 () {});
    </script>
</asp:Content>

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

ASP.NET MVC 3

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:

<head>
    <title>@ViewBag.Title</title>
    <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)
</head>

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

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

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.

Advertisements
 
Leave a comment

Posted by on March 14, 2011 in General

 

Tags: , , , , ,

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 )

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

 
%d bloggers like this: