Q:

Load css dynamically in asp.net? 

I'm creating a content management system where a user can select a css file from their server and the application will parse and store the css.   The application will need to be able to parse the css classes out, record them, and store the css content to be dynamically added to another page where a user can select the different css classes from a drop down.   So does anyone know of a way to add css content to a page dynamically, for example from a database?   I've found a few projects for parsing the css, here .   
Thanks in advance. 

A:

Make a controller which serves the CSS content:
<link rel="stylesheet" href="@Url. Action("GetCss", "Serve", new {id="filename"})" />

Controller code:
public class ServeController: Controller
{
    public ContentResult GetCss(string id)
    {
        string cssBody = GetCssBodyFromDatabase(id);
        return Content(cssBody, "text/css");
    }
}

A:

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";

A:

I think NullReference gave you a MVC solution because you tagged your post "mvc".  If you're using ASP.NET Web forms, you can use the same technique used when generating CSS-links on-the-fly on user-controls.  On the page's Page_Init event, do something like the following (in the example below, I'm linking to jquery-ui-CSS):
protected void Page_Init(object sender, EventArgs e)
{
     System. Web. UI.HtmlControls. HtmlLink jqueryUICSS;
     jqueryUICSS = new System. Web. UI.HtmlControls. HtmlLink();
     jqueryUICSS.Href = "styles/jquery-ui-1.8.13.custom.css");
     jqueryUICSS.Attributes. Add("rel", "stylesheet");
     jqueryUICSS.Attributes. Add("type", "text/css");
     Page. Header. Controls. Add(jqueryUICSS);
}

If you want actual  elements to be rendered on the header, then use HtmlGeneric control instead of HtmlLink in my example above.  It's still the same technique--on Page_Init, add to the Page. Header. Controls collection:
    protected void Page_Init(object sender, EventArgs e)
    {
        System. Web. UI.HtmlControls. HtmlGenericControl mystyles;
        mystyles = new System. Web. UI.HtmlControls. HtmlGenericControl();
        mystyles. TagName = "style";
        string sampleCSS = "body { color: Black; } h1 {font-weight: bold;}";
        mystyles. InnerText = sampleCSS;
        Page. Header. Controls. Add(mystyles);
    }

