2014-11-05 85 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参数来优化缓存。