Dynamically generate CSS file from database in ASP.NET MVC

后端 未结 1 1272
终归单人心
终归单人心 2021-01-31 00:57

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,

相关标签:
1条回答
  • 2021-01-31 00:59

    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 EDIT: 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");
        }
    }
    
    0 讨论(0)
提交回复
热议问题