views:

28

answers:

2

Hi,

I am using MVC 2. I have a master page and a view that uses this master page. I have to use a javascript file for this view only, and not for the other views. What is the best way to add a javascript file to this view? What I currently did was to add the javascript file at the top in my content tag. Is this the best way to do it? I did it as follows:

<asp:Content ID="cntMain" ContentPlaceHolderID="cphMain" runat="server">

     <script src="../../Scripts/myjs.js" type="text/javascript"></script>

</asp:Content>

The content place holder for this content tag in my master page is in a div, so it is complaining that a script tag can not be in a div, and underlines it in green. So I am assuming that there is another decent way of doing this?

Thanks

+2  A: 

Add this to your master page where you want the script to appear

    <asp:ContentPlaceHolder ID="ScriptsContent" runat="server" />

and add this to your view

    <asp:Content ID="Content3" ContentPlaceHolderID="ScriptsContent" runat="server">
       <script src="../../Scripts/myjs.js" type="text/javascript"></script>
    </asp:Content>
danielfishr
A: 

The content place holder for this content tag in my master page is in a div

Move the ContentPlaceHolder to the head section in your master page and use it as normal. Note, although you declare this in the master page, you don't have populate it in any/all of your views.

<head runat="server">
    <title><asp:ContentPlaceHolder ID="TitleContent" runat="server" /></title>
    <link href="../../Content/Site.css" rel="stylesheet" type="text/css" />
    <asp:ContentPlaceHolder ID="cphMain" runat="server"></asp:ContentPlaceHolder>
</head>
Ahmad