Geeks With Blogs

News My Blog has been MOVED to

Michael Freidgeim's OLD Blog My Blog has been MOVED to
More than a year ago I wrote a post Code Render Blocks does not work inside HEAD server controls about the problem, that prevented me to update URL of CSS file, when version of assembly incremented.
Now I've created a function  
       /// <summary>
        /// </summary>
        /// <param name="page"></param>
        /// <param name="cssFileHref">e.g. "~/StyleSheet.css"</param>
        /// <returns></returns>
        public static HtmlLink AddStyleSheetLink(this Page page, string cssFileHref)
            if (page.Header == null) { throw new NullReferenceException("page.Header is null"); }
            HtmlLink link = new HtmlLink();
            link.Href = cssFileHref;
            link.Attributes.Add("rel", "stylesheet");
            link.Attributes.Add("type", "text/css");
            return link;
and called it from markup aspx.

<% //this.AddHeadItems();CSSHelper.AddStyleSheetLink(this,"MyStylesFile.css?v="+Utility.AssemblyVersionNumber()); %> 

Similar function in VB has been described in StyleSheetsManage class for DotNetNuke  post.

Note that I intentionally calling it from markup instead of code behind to be able manually change URL(e.g to ?v57=") without new version rebuild to force refresh of CSS file in client browsers.
Initially it failed with the error:
Additional information: The Controls collection cannot be modified because the control contains code blocks (i.e. <% ... %>).
 , but I was able to delete code render blocks out off HEAD block.
Then I found, that if I am calling AddStyleSheetLink after <HEAD runat="server"> block, the call has no effect and link to CSS file is not inserted.
But when I've put AddStyleSheetLink before HEAD, it works as expected 

<% //this.AddHeadItems();
CSSHelper.AddStyleSheetLink(this,"MyStylesFile.css?v="+Utility.AssemblyVersionNumber()); %>

<HEAD runat="server">
and generates  desired html: 

 <HEAD><meta content="Microsoft Visual Studio 7.0" name="GENERATOR" /><meta content="C#" name="CODE_LANGUAGE" /><meta content="JavaScript" name="vs_defaultClientScript" /><meta content="" name="vs_targetSchema" />
<link href="MyStylesFile.css?v=" rel="stylesheet" type="text/css" />

Alternative approach suggested in automatically-version-your-css-and-javascript-files/ is to append the number to the file name itself and then use RewriteRule processor (e.g. utilizing "URL Rewriting Using ISAPI_Rewrite" )

Posted on Thursday, February 12, 2009 9:13 PM ASP.NET , CSS/DHTML/JavaScript | Back to top

Comments on this post: Insert CSS link with updatable version number in URL

No comments posted yet.
Your comment:
 (will show your gravatar)

Copyright © Michael Freidgeim | Powered by: