Today I had a problem of trying to call a javascript file from my masterpage. I have a script that swaps around the page’s style sheets when a user clicks on a link to increase/decrease the font size. My problem was that the path to the file was wrong if I created a page in a directory lower than where the masterpage is stored.
My solution is to set the path in the PageLoad event in the code behind and call the script then.
Original Code (aspx page):
<html xmlns="http://www.w3.org/1999/xhtml">
<head runat="server">
<title>Therapy Focus</title>
<link href="~/css/default.css" rel="stylesheet" type="text/css" />
<link rel="alternate stylesheet" type="text/css" href="~/css/default.css" title="default" />
<link rel="alternate stylesheet" type="text/css" href="~/css/default2.css" title="default2" />
<link rel="alternate stylesheet" type="text/css" href="~/css/default3.css" title="default3" />
<script type="text/javascript" src="scripts/styleswitcher.js" ></script>
<asp:ContentPlaceHolder id="head" runat="server">
</asp:ContentPlaceHolder>
</head>
<body>
Solution (code behind):
protected void Page_Load(object sender, EventArgs e)
{
string jscriptPath = Request.ApplicationPath + "/scripts/styleswitcher.js";
Page.ClientScript.RegisterClientScriptInclude(UniqueID, jscriptPath);
}
Filed under: ASP.NET, C#, Javascript