1

I feel like I'm either really close on this, or miles away - MVC/Razor isn't yet in my wheelhouse. I've looked at too many "Dynamic CSS" links in SO and elsewhere to list.

I have a static CSS file (~/Content/site.css) that I want to add additional CSS classes to (in my case, based on data from a database).

I created the following:

public class CssController : Controller
{
    private string GetCustomCss()
    {
        var builder = new StringBuilder();
        var colorInfo = mRepository.GetColors();

        foreach (var detail in colorInfo.ResultValue)
        {
            builder.Append(detail.CustomName);
            builder.Append("-light-color");
            builder.Append(" { ");
            builder.Append("color: ");
            GetLightColor(detail, builder);
            builder.Append("; ");
            builder.Append(" } ");
            }
        }            
        return builder.ToString();
    }

    public ContentResult DynamicCss()
    {
        var siteCss = string.Format("{0}{1}", 
            System.IO.File.ReadAllText(Server.MapPath("/Content/Site.css")), 
             GetCustomCss());
        return Content(siteCss, "text/css");
    }
}

And in my _Layout file:

<head>
    <link href="@Url.Action("DynamicCss", "CssController")" 
          rel="stylesheet" 
          type="text/css" />
</head>

I guess I'd like to know what my bug is with this code, but if there is another "Best Practice" that you could point me to, I'd appreciate it.

1 Answer 1

3

I'm not sure if there is a best practice here, but one option may be an HttpHandler that reads that supplements an existing css file.

First, add a handler.

using System.Web;

namespace MyApp.Infrastructure
{
    public class DynamicCss : IHttpHandler
    {
        public bool IsReusable {
            get {
                return true;
            }
        }

        public void ProcessRequest(HttpContext context)
        {
            //original css file
            var path = HttpContext.Current.Server.MapPath("~/Content/bootstrap.css");

            HttpContext.Current.Response.ContentType = "text/css";
            HttpContext.Current.Response.TransmitFile(path);
            //Add other your custom components  
            HttpContext.Current.Response.Write(".other {color:blue}"); 
            HttpContext.Current.Response.Flush();
        }
    }
}

Next, register the handler in the web.config.

  <system.webServer>
    <handlers>
      <add name="dynamicCss" path="myCss.cssx"  verb="*"
           type="MyApp.Infrastructure.DynamicCss" />
    </handlers>
  </system.webServer>

Almost done. Make sure that MVC ignores the new cssx extension.

   public class RouteConfig
    {
        public static void RegisterRoutes(RouteCollection routes)
        {
            routes.IgnoreRoute("{resource}.cssx"); //Added this line
            routes.IgnoreRoute("{resource}.axd/{*pathInfo}");

            routes.MapRoute(
                name: "Default",
                url: "{controller}/{action}/{id}",
                defaults: new { controller = "Home", action = "Index", id = UrlParameter.Optional }
            );
        }
    }

Finally, link to it in the _layout

   <link href="~/sitecss.cssx" rel="stylesheet"  type="text/css"/>
Sign up to request clarification or add additional context in comments.

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.