Dynamic CSS for ASP.NET MVC?

I'd love to be able to run my CSS through Razor

What stops you?

public class CssViewResult : PartialViewResult
{
    public override void ExecuteResult(ControllerContext context)
    {
        context.HttpContext.Response.ContentType = "text/css";
        base.ExecuteResult(context);
    }
}

public class HomeController : Controller
{
    public ActionResult Index()
    {
        return new CssViewResult();
    }
}

and in ~/Views/Home/Index.cshtml:

@{
    var color = "White";
    if (DateTime.Now.Hour > 18 || DateTime.Now.Hour < 8)
    {
        color = "Black";
    }
}
.foo {
    color: @color;
}

Now all that's left is to include it:

<link href="@Url.Action("index")" rel="stylesheet" type="text/css" />

You can also make the template strongly typed to a view model, write loops, ifs, inclusions, ...


Phil Haack has made a blog post about LessCSS and .net:

http://haacked.com/archive/2009/12/02/t4-template-for-less-css.aspx


A slight modification of @darin-dimitrov's answer. This adds the ability to pass in a model to the CssView:

public class CssViewResult : PartialViewResult
{
    public CssViewResult()
    {

    }

    public CssViewResult(object model)
    {
        if (model != null)
        {
            ViewData.Model = model;
        }
    }

    public override void ExecuteResult(ControllerContext context)
    {
        context.HttpContext.Response.ContentType = "text/css";
        base.ExecuteResult(context);
    }
}

and then you just consume it with:

return new CssViewResult(model);