10,000 Monkeys - Harnessing the Power of Typing Monkeys

America's 2,672,401st Most Read Blog by Kevin Marshall.
in

ASP.NET 2005 Annoyances #00001 - Master Pages & Javascript Files

This is my first post in an ongoing series of things that annoy me about ASP.NET in VS2005.  Issue #00001, when using a MasterPage, any content pages not in the same directory as the master pages cannot use any javascript linked like so:

<script language="javascript" type="text/javascript" src="/Scripts/myscript.js"></script>
 
Normally when using a masterpage, you can make a reference to something using "~/subdir/file" on a server control in a content page and it will convert the url based on the content page's location in the folder structure. Since <script> tags cannot be set to runat="server", the reference to a file is not converted and the content page won't be able to access the javascript. I tried a couple of different ways of trying to change the reference dynamically on the script tags, but the easiest fix seemed to be to make my own control to write out html <script> tag.  Something like this will mimic the attributes of a normal <script> tag, but it will adjust the source on any conent pages that aren't in the root.
 
 public class ServerScript : Control
    {
        
private string _src = string.Empty;
        private string 
_language "javascript";
        private string 
_type "text/javascript";
        private const string 
HTML_CODE "<script language=\"{0}\" src=\"{1}\" type=\"{2}\"></script>";

        public string 
src
        {
            
get return _src}
            
set { _src = value; }
        }

        
public string language
        {
            
get return _language}
            
set { _language = value; }
        }

        
public string type
        {
            
get return _language}
            
set { _language = value; }
        }

        
public override void RenderControl(HtmlTextWriter writer)
        {
            writer.Write(
string.Format(HTML_CODE, _language, ResolveClientUrl(_src), _type));
        
}
}

Posted: Feb 17 2006, 10:56 AM by kmarshall | with no comments
Filed under:

Comments

No Comments

Leave a Comment

(required) 

(required) 

(optional)

(required)