2

in my ASP.NET app, I'm trying to add a CSS reference dynamically (with intelligent caching on the client).

My code renders to the browser correctly, but it doesn't load the CSS file. I have to put the link in my markup explicitly for the CSS file to load, but it won't load when in code behind

protected void Page_Load(object sender, EventArgs e)
{
    if (!Page.IsPostBack)
    {
        FileInfo fi = new FileInfo(Server.MapPath("~/Styles/Site.css"));
        HtmlGenericControl link = new HtmlGenericControl("LINK");
        link.Attributes.Add("rel", "stylesheet");
        link.Attributes.Add("type", "text/css");
        link.Attributes.Add("href", "~/Styles/Site.css?t=" + fi.CreationTime.Ticks.ToString());
        Page.Header.Controls.Add(link);
    }
}

This seems really simple. Not sure why it isn't working.

NOTE: the attending the fileinfo ticks has no effect on the behavior. It renders fine but doesn't load regardless of appending the file information.

1 Answer 1

2

You need to resolve the client URL for the stylesheet and then it will work:

link.Attributes.Add("href", ResolveClientUrl("~/Styles/Site.css?t=" + fi.CreationTime.Ticks));
Sign up to request clarification or add additional context in comments.

2 Comments

awesome! Thank you! I am curious though: the rendered code looks the same. Do you know why this makes a difference? Is it about the way ASP.NET/IIS loads the dynamic files like CSS files?
@pearcewg without the ResolveClientUtl() call it still has the ~/ in the markup <LINK rel="stylesheet" type="text/css" href="~/Styles/Site.css?t=634534960310240974"></LINK> whereas it's resolved otherwise <LINK rel="stylesheet" type="text/css" href="Styles/Site.css?t=634534960310240974"></LINK>

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.