Using C# to Dynamically Generate CSS Files

Using C# to dynamically generate CSS files

Instead of a Web Control, you're likely better off creating a Generic Handler. This won't have the overhead that a web control has.

  1. In your handler, accept the clientID via querystring - this allows you to cache on a client level
  2. In your .master file, you can link to it < link src="MyCssHandler.ashx?ClientID=<%=ClientID%>" >

In your handler you have a few ways to work with the CSS.

  1. Just have a bunch of response.write for the css, and put in relevant client values
  2. Create an external CSS file with it's own special identifier - maybe <% %>. You could then load all the client specific values in a NameValuePair Collection, and then loop through the external CSS file, parsing <% NAME %> and replacing with the correct value. Then response.write this file. More complicated true but it allows for a hell of a lot cleaner CSS files

Dynamically Change A CSS Class's attributes in C#

Generally this is handled in a few different ways. You could include an additional or different CSS file based on properties of the request (e.g. current site). You could also output HTML that includes different classes based on request properties. A common technique is to add classes to root elements like or when certain conditions are met, and then write CSS to make use of those classes.

For example, if you are using the same code base for multiple sites, on site A you could have <html class="site-a"> and on site B you'd have <html class="site-b">. Then you can override styles based on the site easily.

/* Default to white background */
body {
background: white;
}

/* Use a black background for Site A */
.site-a body {
background: black;
}

/* Use a blue background for Site B */
.site-b body {
background: blue;
}

This is of course a very simple example. In the case of entire sites, separate CSS files makes more architectural sense, as you'd store them along with other site specific files.

I recommend studying more around how applications typically organize their front end presentation layers and files. For example, MVC is a way to separate out parts of an application. Within the context of presentation, you have concepts like templates and themes to encapsulate parts of the UI and turn it into reusable parts.

EDIT: Lost in my answer is that I didn't talk about actually dynamically generating CSS files. This is because dynamically generating CSS files is uncommon and generally not the right solution to a problem. As commentors have pointed out, there are CSS preprocessors like LESS and SASS which are generally targeted at solving some of CSSs internal issues (mostly redundancy). Preprocessors fix problems with CSS and are extremely useful, but aren't used in the way that it sounds like you've asked about. Separate CSS files or CSS files that key off of different classes and IDs are the solution, not dynamically creating a CSS file or block with different property values.

C#.NET: Change elements in a CSS file from dynamically generated HTML?

Since you say "code behind file"... are you doing this in ASP.NET?

You could use String.Replace functions in the HTML code to change <link href="www.example.com/cssfile.css"> to <link href="fixcss.ashx?file=www.example.com/cssfile.css">. Then write a fixcss.ashx to retrieve the CSS file and perform the string replacements on it.

Change CSS Dynamically

I think I've found what I am looking for :

protected void Page_Init(object sender, EventArgs e)
{
HtmlLink css = new HtmlLink();
css.Href = "css/fancyforms.css";
css.Attributes["rel"] = "stylesheet";
css.Attributes["type"] = "text/css";
css.Attributes["media"] = "all";
Page.Header.Controls.Add(css);
}

Also MSDN was describing how to achieve this : HtmlLink Class

dynamic generation of CSS attributes in CSS files based on user input in ASP MVC

I got some of it working via dotless just seems a bit old, wondering if its still maintained.

Dynamically generate CSS file from database in ASP.NET MVC

I think the simplest way would be to add something like the following action method to a controller:

public class CssController : Controller {
public ActionResult GetCss() {
StringBuilder sb = new StringBuilder();
Dictionary<string, string> cssValues = new Dictionary<string, string>();
// populate dictionary with values from your database
sb.AppendLine(".myDivClass {");
foreach (var entry in cssValues) {
sb.AppendLine(entry.Key + ": " + entry.Value);
}
sb.AppendLine("}");
return Content(sb.ToString(), "text/css");
}
}

Now in your page you can reference it like so:

<link href="<%: Url.RouteUrl(new { controller=  "CssController", action = "GetCss" }) %>" rel="stylesheet" type="text/css" />

OP EDIT: I made some small changes to the method, but the general premise remains. This is the version I used:

public class CssController : Controller
{
public ContentResult GetTheme()
{
var builder = new StringBuilder();
IDictionary<string, IDictionary<string, string>> css = new Dictionary<string, IDictionary<string, string>>();

/* Populate css object from the database */

foreach (var selector in css)
{
builder.Append(selector.Key);
builder.Append(" { ");
foreach (var entry in selector.Value)
{
builder.Append(string.Format("{0}: {1}; ", entry.Key, entry.Value));
}
builder.AppendLine("}");
}

return Content(builder.ToString(), "text/css");
}
}

Load css dynamically in asp.net?

A good approach for a WebForms-only project is to link to an .ashx handler in your page instead of a static CSS file:

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

Then create the handler (add a 'Generic Handler' item from Visual Studio) and within it you can load the CSS from a database or wherever. Just make sure you set the content type correctly in the handler, so that browsers recognise the response as a valid stylesheet:

context.Response.ContentType = "text/css";


Related Topics



Leave a reply



Submit