ASP.NET MVC - 动态样式表

5

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

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

网站主页面,

<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;
        }
    }
}
3个回答

2
创建多个CSS文件并替换指令在性能方面要好得多。缺点是您需要维护几个CSS文件,它们都做相同的事情但使用不同的颜色。因此,我建议创建一个“通用”CSS文件。对于每种可能的配置(背景颜色等),创建其自己的CSS文件。这样,客户端将缓存,Web服务器将提供静态文件。

1

好的,为了与您发布的实现保持一致,我认为您不需要将CSS文件名传递给处理程序。只需从会话中提取用户ID并查询数据库以获取其背景颜色,而不是从文件中读取。或者,如果您想允许匿名用户选择颜色,只需将其存储在处理程序检查的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"];

然后从那里开始。


0
我认为更好的方法是使用一个CSS文件,其中有各种类,并通过传递类名称到你的body标签来实现这个效果:
.black {background:#000}
.blue {background:#00f}

并且可以找到一种方法来编写脚本,使其呈现为<body class="black>或者创建一个新的WebControl,它呈现为<body>(并给它一个渲染选项,以便根据上下文来确定它应该做什么)。

这些方法可以让您将所有CSS放在一个地方,而无需编辑真正的代码来更改特定类别的颜色,您只需要编辑CSS即可。


网页内容由stack overflow 提供, 点击上面的
可以查看英文原文,
原文链接