2016-05-14 88 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"/>