ASP.NET MVC - 动态样式表

时间:2009-05-15 13:16:13

标签: asp.net-mvc stylesheet

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

根据以下website,我可以在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 个答案:

答案 0 :(得分:2)

创建多个CSS文件并替换&lt;链接&gt;指令要好得多,表现明智。

缺点是你需要维护几个CSS文件,它们都用不同的颜色做同样的事情。 所以我要做的是创建一个通用 css文件。然后对于每种可能的配置(背景颜色,你有什么),创建自己的CSS文件。 //假设合理数量的组合

这样,客户端将缓存,Web服务器将提供静态文件。

答案 1 :(得分: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"];

然后从那里开始。

答案 2 :(得分:0)

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

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

要么找到一种方法来编写body标记的脚本,以便呈现<body class="black>或创建一个呈现为WebControl的新<body>(并为其提供一个查找上下文的呈现选项)找出它应该做的事情。

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

相关问题