动态生成的数据库在ASP.NET MVC中的CSS文件 [英] Dynamically generate CSS file from database in ASP.NET MVC

查看:152
本文介绍了动态生成的数据库在ASP.NET MVC中的CSS文件的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我在找一些基本的主题支持添加到我的web应用程序,与用户能够自定义外观的各个部分。这些包括像颜色,文字大小,字体,其他的基本的东西。我将在数据库中存储这些和每一个页面被访问时装载它们。

I'm looking to add some basic theme support to my web application, with users being able to customise various parts of the look. These include things like colours, text sizes, fonts, other basic things. I will be storing these in the database and loading them each time a page is accessed.

我的问题是,我怎么去生成基于这些数据库值动态CSS文件?

My question is, how do I go about generating a dynamic CSS file based upon these database values?

我想preFER做一些事情,是缓存能干,但可扩展的,如果我想添加更多的编辑风格那就不是有点问题。

I would prefer to do something that is cache-able, but extensible so that if I want to add more editable styles then it wouldn't be a bit issue.

推荐答案

我觉得最简单的方法是添加类似下面的操作方法到控制器:

I think the simplest way would be to add something like the following action method to a controller:

public class CssController : Controller {
    public ActionResult GetCss() {
        StringBuilder sb = new StringBuilder();
        Dictionary<string, string> cssValues = new Dictionary<string, string>();
        // populate dictionary with values from your database
        sb.AppendLine(".myDivClass {");
        foreach (var entry in cssValues) {
            sb.AppendLine(entry.Key + ": " + entry.Value);
        }
        sb.AppendLine("}");
        return Content(sb.ToString(), "text/css");
    }
}

现在在你的页面,你可以参考它像这样:

Now in your page you can reference it like so:

<link href="<%: Url.RouteUrl(new { controller=  "CssController", action = "GetCss" }) %>" rel="stylesheet" type="text/css" />

OP编辑:我做了一些小的改动的方法,但一般premise依然存在。这是我用的版本:

OP I made some small changes to the method, but the general premise remains. This is the version I used:

public class CssController : Controller
{
    public ContentResult GetTheme()
    {
        var builder = new StringBuilder();
        IDictionary<string, IDictionary<string, string>> css = new Dictionary<string, IDictionary<string, string>>();

        /* Populate css object from the database */

        foreach (var selector in css)
        {
            builder.Append(selector.Key);
            builder.Append(" { ");
            foreach (var entry in selector.Value)
            {
                builder.Append(string.Format("{0}: {1}; ", entry.Key, entry.Value));
            }
            builder.AppendLine("}");
        }

        return Content(builder.ToString(), "text/css");
    }
}

这篇关于动态生成的数据库在ASP.NET MVC中的CSS文件的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆