您可以创建一个自定义视图引擎:
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);
}
}
并在以下位置使用自定义扩展名注册它Application_Start
:
ViewEngines.Engines.Add(new CSSViewEngine());
RazorCodeLanguage.Languages.Add("cscss", new CSharpRazorCodeLanguage());
WebPageHttpHandler.RegisterExtension("cscss");
并在 web.config 中将扩展与构建提供程序相关联:
<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>
[注意,如果您遇到程序集绑定错误,您可能需要更改扩展类型中的版本号以匹配您的 Razor 引擎版本。您可以通过查看对项目中 System.Web.WebPages.Razor 程序集的引用的属性来检查您使用的版本]
最后一步是拥有一些控制器:
public class StylesController : Controller
{
public ActionResult Foo()
{
var model = new MyViewModel
{
Date = DateTime.Now
};
return View(model);
}
}
和相应的视图: ( ~/Views/Styles/Foo.cscss
):
@model AppName.Models.MyViewModel
/** This file was generated on @Model.Date **/
body {
background-color: Red;
}
现在可以将其作为样式包含在布局中:
<link href="@Url.Action("Foo", "Styles")" rel="stylesheet" type="text/css" />