Using CSS within ASCX Files

I was trying to add some more style into the WoW Guild Roster module I'm writing, but I ran into an issue that stumped me for quite a while - how to link to the CSS file.

The issue with linking to a Cascading Style Sheet (CSS) was problematic on two fronts:

  1. DotNetNuke development is done via ASCX files, and not ASPX files
    This means that I'm coding for the control, and not the page. As such, I never quite know where the location context of the rendering is occurring.
  2. DotNetNuke uses some rather unfriendly URLs
    The web browser sees something more like this:
    https://www.mywebsite.com/WebSiteInformation/DNNWebPage/tabid/167/Default.aspx
    This poses all kinds of obvious problems, taking my first point and multiplying it a few more times over.

Needless to say, I was convinced that using the standard <link> call wasn't looking too useful at this point. After looking around and playing with the code for 20-30 minutes, there's a couple routes to go for this:

  • Use a hard-coded URL such as:
    <link rel='stylesheet' type='text/css' href='/DesktopModules/MyModuleName/customModuleStyles.css' />
  • Create a custom function in your code-behind to handle the URL (as discussed by Milan in his on Stylesheets and Master pages blog post a couple years ago)
  • Use the ResolveUrl() method so that it looks like:
    <link rel='stylesheet' type='text/css' href='<%= ResolveUrl("~/DesktopModules/MyModuleName/customModuleStyles.css") %>' />

I ended up using with the third option, quite happily, and thought I would share here.

Comments