Dynamic Stylesheets Using Razor

前提是你 提交于 2019-11-28 06:29:57
Darin Dimitrov

You could create a custom view engine:

public class CSSViewEngine : RazorViewEngine
{
    public CSSViewEngine()
    {
        ViewLocationFormats = new[] 
        { 
            "~/Views/{1}/{0}.cscss", 
            "~/Views/Shared/{0}.cscss" 
        };
        FileExtensions = new[] { "cscss" };
    }

    protected override IView CreateView(ControllerContext controllerContext, string viewPath, string masterPath)
    {
        controllerContext.HttpContext.Response.ContentType = "text/css";
        return base.CreateView(controllerContext, viewPath, masterPath);
    }
}

and also register it with a custom extension in Application_Start:

ViewEngines.Engines.Add(new CSSViewEngine());
RazorCodeLanguage.Languages.Add("cscss", new CSharpRazorCodeLanguage());
WebPageHttpHandler.RegisterExtension("cscss");

and inside web.config associate the extension with a build provider:

<compilation debug="true" targetFramework="4.0">
    <assemblies>
        ...
    </assemblies>

    <buildProviders>
        <add extension=".cscss" type="System.Web.WebPages.Razor.RazorBuildProvider, System.Web.WebPages.Razor, Version=3.0.0.0, Culture=neutral, PublicKeyToken=31bf3856ad364e35"/>
    </buildProviders>
</compilation>

[note, if you get an assembly binding error you might need to change the version number in the extension type to match your version of the Razor engine. You can check which version you are using by looking at the properties of your reference to the System.Web.WebPages.Razor assembly in your project]

And the last step is to have some controller:

public class StylesController : Controller
{
    public ActionResult Foo()
    {
        var model = new MyViewModel
        {
            Date = DateTime.Now
        };
        return View(model);
    }
}

and a corresponding view: (~/Views/Styles/Foo.cscss):

@model AppName.Models.MyViewModel

/** This file was generated on @Model.Date **/

body {
    background-color: Red;
}

which could now be included as a style in the Layout:

<link href="@Url.Action("Foo", "Styles")" rel="stylesheet" type="text/css" />
易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!