Best way to insert server-side variables / function results in CSS in ASP.NET?

My ASP.NET application has some server side methods, the results of which I would like to inject into my CSS files. For example, instead of hard-coding the logo url, I would like to insert a call to MyHelperClass.GetCurrentLogoUrl () in the middle of the CSS file.

If I was writing an ASPX page, I could use the x code renderer (ie stuff like "<% = MyHelperClass. GetCurrentLogoUrl ()%>") in the middle of my HTML markup. It would be nice to do something like this for CSS.

There are some preliminary CSS routines for example. and they seem to have some interesting functionality, but I don't know which one supports making C # calls like this.


source to share

4 answers

You can just create an aspx page and link it to include a stylesheet. However, you will miss the css highlighting.

<link href="" type="text/css" rel="stylesheet">


This can potentially cause unnecessary overhead, especially if most of the properties you change do not change at runtime. In this case, you might need to examine the TT files that mostly generate other files when deployed - in your case you could generate css with any complex logic.



David P's answer to Automatically resolving ASP.NET MVC URLs in CSS files suggests one approach. If you give your CSS files the .aspx extension, then use a page directive to tell ASP.NET that it is actually a CSS file, like

<%@ Page Language="C#" ContentType="text/css" %>


then you can write CSS, but also use regular ASP.NET code rendering blocks. It's a little weird to name the CSS.aspx files, but the original test suggests it might work.

UPDATE : The props on ov to indicate this is even faster than me.



You can enter the class name in html, something like:

<input type="text" id="myTextBox" cssClass="<%=myClassName%>" />


You can also change the class name in the code using the .attributes method.



Add the following to your section <head></head>

on the page

<style runat="server" id="cssPhoneResize" type="text/css"></style>


Then from your server side method:

string logoUrl = "/images/logo2.jpg";
cssPhoneResize.InnerHtml += "#Image{-image: url(" + logoUrl + ");}";


Hope this helps!



All Articles