user3086751
user3086751

Reputation: 205

Adding CSS at runtime to an ASP.net master page.

I have an ASP.net web application, and would like to know if is it possible to change the CSS of a site at run time of a master page, and get the CSS file name from a SQL database and add it into the system ?

Upvotes: 0

Views: 2809

Answers (5)

Awais Saleem
Awais Saleem

Reputation: 71

Creating a new element dynamically

const styleElement = document.createElement("style");

// Adding custom CSS rules
styleElement.textContent = `
  /* Your CSS rules here */
.test { color:red;}
`;

// Appending the <style> element to the <head> section of the HTML document
document.head.appendChild(styleElement);

Upvotes: 0

You can put on the top of the masterpage on aspnet literal and construct the link in the pageload of the masterpage that way you could put a css there

<asp:Literal ID="Css" runat="Server" />

Then on the page load

var cssfilename  = GetCssFromDatabase();
Literal.Text = "<link rel=\"stylesheet\" media=\"all\" " + cssfilename  + "\" />";

Upvotes: 2

Hardik Mer
Hardik Mer

Reputation: 836

There are several ways you can achieve this.

Best way I suggest you to use theme and skin file concept.

    protected void Page_PreInit(object sender, EventArgs e)
    {
    switch (Request.QueryString["theme"])
    {
    case "Blue":
        Page.Theme = "BlueTheme";
        break;
    case "Pink":
        Page.Theme = "PinkTheme";
        break;
    }
    }

here you can change the values of your theme run-time from code behind accurately. you can put your .css files into different themes. and as per database conditions you can change values of theme files.

hope this will help.

Upvotes: 0

Robert Fricke
Robert Fricke

Reputation: 3643

Yes it is. Use <head runat="server"> and you can put anything in there, simplest way probably a Literal control where you append the string from codebehind

Masterpage.master:

<head runat="server">
    <title>Your Site</title>
    <asp:Literal runat="server" ID="cssLiteral" />
</head>

Masterpage.master.cs:

cssLiteral.Text = "<link rel='stylesheet' type='text/css' href='"+strCssFileName+"' />";

Upvotes: 1

Esko
Esko

Reputation: 4207

You haven't provided much information of your case, yes it's possible in many ways. Here is a simple example how to change css-file in master-page from a content page:

First add a static variable for example in Global.asax (code in VB.Net)

Public Shared DefaultCssFile As String = "~/MyStyles.css"

In master pages header:

<asp:PlaceHolder runat="server">
    <link rel="Stylesheet" type="text/css" href="<%= Page.ResolveUrl(MyApp.Global_asax.DefaultCssFile) %>" />
</asp:PlaceHolder> 

Then just change the variables value as you see fit.

MyApp.Global_asax.DefaultCssFile = "~/MyOtherStyles.css"

Upvotes: 0

Related Questions