2014-11-05 105 views
0

在我的MVC應用程序中,我想應用主題。所以,我試圖加載從BundleConfig正在被Global.asax中像如何動態加載CSS

BundleConfig.RegisterBundles(BundleTable.Bundles); 

但是初始化上App.Start()方法的CSS文件,我想動態加載的CSS來改變顯示風格(主題)頁面上的下拉列表或鏈接按鈕。

我該怎麼做?我試圖在BaseController中編寫,然後從那裏調用'RegisterBundles'方法但它不起作用。

對此的任何幫助表示讚賞。

回答

0

一種動態CSS的解決方案是你的主題的CSS項在您的標記鏈接到一個MVC控制器動作,傳遞主題/客戶ID,EQ:

<link rel="stylesheet/less" type="text/css" href='@Url.Action("ThemeCss","Render", new { id = Model.AccountID})' /> 

和ThemeCss操作方法可能會返回內容如下:

[HttpGet] 
    [OutputCache(NoStore = true, Duration = 0, VaryByParam = "None")] 
    public ActionResult ThemeCss(int id) //accountID 
    { 
     Account account = Db.GetInstance().Accounts.FirstOrDefault(a => a.AccountID == id); 
     AccountSite site = account.AccountSite; 
     string col1, col2, col3, col4; 
     if (site.Theme == null) //custom colour theme 
     { 
      col1 = site.ThemeColour1; 
      col2 = site.ThemeColour2; 
      col3 = site.ThemeColour3; 
      col4 = site.ThemeColour4; 
     } 
     else 
     { 
      col1 = site.Theme.PrimaryColour.Substring(1); 
      col2 = site.Theme.SecondaryColour.Substring(1); 
      col3 = site.Theme.OtherColours.Split(',')[0].Substring(1); 
      col4 = site.Theme.OtherColours.Split(',')[1].Substring(1); 
     } 
     string lessFile = "custom"; 
     string less = System.IO.File.ReadAllText(Server.MapPath("~/Content/render/themes/" + lessFile + ".less")); 
     less = Regex.Replace(less, @"(\d){6}", 
          delegate(Match match) 
          { 
           switch (match.Groups[1].Value) 
           { 
            case "1": 
             return col1 ?? "E6E6E6"; 
            case "2": 
             return col2 ?? "B1B1B1"; 
            case "3": 
             return col3 ?? "333333"; 
            default: //case "4": 
             return col4 ?? "FFFFFF"; 
           } 
          }); 
     return new ContentResult() { Content = less, ContentType = "text/css" }; 
    } 

與捆綁相比,此解決方案的缺點是您在CSS縮小上失敗了。如果您的主題將按照AccountID進行修復,那麼您可以通過將OutputCache屬性更改爲id參數來優化緩存。