ASP.NET MVC - 动态样式表

Ros*_*Ros 5 asp.net-mvc stylesheet

我想让用户选择网站的背景颜色并将所选颜色保存在数据库中.当人登录背景时,将显示正确的颜色.

基于以下网站,我可以在CssHandler.ashx文件中设置颜色.但是,从数据库获取信息的最佳方法是什么?

网站母版页,

<link href="../../Content/CSSHandler.ashx?file=Site.css" rel="stylesheet" type="text/css" />
Run Code Online (Sandbox Code Playgroud)

的site.css,

header
{
    background-color:#BG_COLOR#;
}
Run Code Online (Sandbox Code Playgroud)

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;
        }
    }
}
Run Code Online (Sandbox Code Playgroud)

Oli*_*Oli 0

我认为更好的方法是使用一个包含各种类的 CSS 文件,并将类名传递给您的 body 标记:

.black {background:#000}
.blue {background:#00f}
Run Code Online (Sandbox Code Playgroud)

要么找到一种方法来编写正文标记以便它呈现<body class="black>,要么创建一个新的WebControl呈现为<body>(并为其提供一个呈现选项,该选项会根据上下文来确定它应该做什么。

通过这些方式,您可以将所有 CSS 保存在一处,并且无需编辑实际代码来更改某一特定类的颜色,只需编辑 CSS 即可。