2016-05-14 86 views
1

我觉得我要么离得很近,要么就在几英里之外--MVC/Razor还没有在我的驾驶室中。我在SO和其他地方看过太多“动态CSS”链接列出。将动态CSS添加到MVC中的静态CSS文件内容

我有一个静态CSS文件(〜/ Content/site.css),我想添加额外的CSS类(在我的情况下,基于数据库中的数据)。

我创建了以下内容:

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"); 
    } 
} 

在我_layout文件:

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

我想我想知道我的错误是在这段代码是什么,但如果有另一个“最佳实践”,你可以指向我,我会很感激。

回答

3

我不确定这里是否有最佳做法,但有一个选项可能是HttpHandler读取补充现有css文件。

首先,添加一个处理程序。

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(); 
     } 
    } 
} 

接下来,在web.config中注册处理程序。

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

几乎完成。确保MVC忽略新的cssx扩展。

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 } 
      ); 
     } 
    } 

最后,链接到它在_layout

<link href="~/sitecss.cssx" rel="stylesheet" type="text/css"/>