ASP.NET MVC - dynamic style

I want the user to select the background color for the website and save the selected color in the database. When a person enters the background, the correct color will be displayed.

Based on the following site , I can set the color in the file CssHandler.ashx. But what is the best way to get information from a database?

The main page of the site,

<link href="../../Content/CSSHandler.ashx?file=Site.css" rel="stylesheet" type="text/css" />

site.css

header
{
    background-color:#BG_COLOR#;
}

CssHandler.ashx,

public class CssHandler : IHttpHandler
{

    public void ProcessRequest(HttpContext context)
    {
        context.Response.ContentType = "text/css";

        // Get the file from the query stirng
        string File = context.Request.QueryString["file"];

        // Find the actual path
        string Path = context.Server.MapPath(File);

        // Limit to only css files
        if (System.IO.Path.GetExtension(Path) != ".css")
            context.Response.End();

        // Make sure file exists
        if (!System.IO.File.Exists(Path))
            context.Response.End();

        // Open the file, read the contents and replace the variables
        using (System.IO.StreamReader css = new System.IO.StreamReader(Path))
        {
            string CSS = css.ReadToEnd();
            CSS = CSS.Replace("#BG_COLOR#","Blue");
            context.Response.Write(CSS);
        }
    }

    public bool IsReusable
    {
        get
        {
            return false;
        }
    }
}
+5
source share
3 answers

Creating multiple CSS files and <link> substitution is much better, performance wise.

- CSS, . , , css. ( , ) CSS.//

, , - .

+2

, , , CSS . . , , cookie, .

, ...

// Get the file from the query stirng
string File = context.Request.QueryString["file"];

...

// Get user ID from session
int userId = Convert.ToInt32(Session["UserId"]));
// Now, pull background color from database

...

// Get background color preference from cookie
HttpCookie cookie = Request.Cookies["Preferences"];
string bgColor = cookie["BackgroundColor"];

.

+1

, CSS body:

.black {background:#000}
.blue {background:#00f}

script body, <body class="black> WebControl, <body> ( , , , .

These methods allow you to save all the CSS in one place, and you do not need to edit the real code to change the color for one specific class, you just edit the CSS.

0
source

All Articles