Search code examples
asp.netjavascriptmaster-pagescontentplaceholder

Embedded Javascript in Master Page or Pages That Use Master Page throw "Object Expected Error"


I'm semi-new to writing ASP.Net applications using master pages and I've run into an issue I've spent some time on but can't seem to solve.

My situation is that I have a master page with a structure that looks like this:

<head runat="server"> 
    <title>Test Site</title>   
    <link rel="Stylesheet" type="text/css" href="Default.css" />
    <script type="text/javascript" language="javascript" src="js/Default.js" />
    <meta http-equiv="Expires" content="0"/>
    <meta http-equiv="Cache-Control" content="no-cache"/>
    <meta http-equiv="Pragma" content="no-cache"/>        
    <asp:ContentPlaceHolder ID="cphHead" runat="server">
    </asp:ContentPlaceHolder>
</head>
<body>
    <form id="form1" runat="server">       

        <div id="divHeader">
        <asp:ContentPlaceHolder ID="cphPageTitle" runat="server"></asp:ContentPlaceHolder>
        </div>

        <div id="divMainContent">
        <asp:ContentPlaceHolder ID="cphMainContent" runat="server"></asp:ContentPlaceHolder>
        </div>
    </div>
    </form>
</body>

I then have a page that uses this master page that contains the following:

<asp:Content ContentPlaceHolderID="cphHead" runat="server">   
    <script type="text/javascript" language="javascript" >    

        function test() {
            alert("Hello World");
        }
 </script>
</asp:Content>

<asp:Content ContentPlaceHolderID="cphMainContent" runat="server">
    <fieldset>          
        <img alt="Select As Of Date" src="Images/Calendar.png" id="aAsOfDate" class="clickable" runat="server" onclick="test();" />            
        <asp:Button runat="server" CssClass="buttonStyle" ID="btnSubmit" Text="Submit" OnClick="btnSubmit_Clicked"/>            
    </fieldset> 
</asp:Content>

When I run this page and click on the image I get an "Object Expected" error.

However, if I place the test function into my Default.js external file it will function perfectly.

I can't seem to figure out why this is happening. Any ideas?


Solution

  • EDIT:

    Try using an http analyzer like fiddler (fiddler2.com/fiddler2) to see if the script is actually loading. The issue is probably that the relative path of the aspx page is incorrect for the script you're loading. The path is always relative to the executing aspx, not the location of the Master Page. If the script isn't loaded, the function test() never exists hence the error.

    Try this in your header to make sure the path is always correct

    <script type="text/javascript" language="javascript" src='<%= Page.ResolveClientUrl("~/js/Default.js") %>' ></ script>

    instead of

    <script type="text/javascript" language="javascript" src="js/Default.js" />