在頁面上可以用@Styles.Render("~/Content/css") 來加載css
首先要在App_Start 里面BundleConfig.cs 文件里面 添加要包含的css文件
BundleConfig就是一個微軟新加的 一個打包的配置類
用來Add 各種Bundle
bundles.Add(new StyleBundle("~/Content").Include("~/Content/common.css")); //這樣是錯誤的 new StyleBundle("~/Content") 初始化的虛擬目錄名稱不能跟 真正的目錄相同 也就是 后面的Include("~/Content/common.css")); 這里要把new StyleBundle("~/Content")的"~/Content" 改成別的名稱。
bundles.Add(new StyleBundle("~/Content1").Include("~/Content/common.css", "~/Content/content.css")); bundles.Add(new StyleBundle("~/Content2").Include("~/Content/site.css" ));
這里的"~/Content1" 可以隨便起名(但一定要按這個URL格式來) 用於標記打包哪個文件夾下面的.css 文件,后面的Include方法接受的是一個string[] 根據傳入的路徑去對css文件進行打包
然后前面頁面用@Styles.Render("~/Content1”,"~/Content2”) 來調用顯示。
bundles.Add(new StyleBundle("~/Content1").Include("~/Content/content.css")); bundles.Add(new StyleBundle("~/Content1").Include("~/Content/site.css")); bundles.Add(new StyleBundle("~/Content1").Include("~/Content/common.css"));
這種情況添加相同的Key時 程序會調用最后一次添加的~/Content/common.css。
當然也可以直接在頁面上來加載比如:
(2).@Styles.Render("~/Content/site.css", "~/Content/common.css", "~/Content/content.css")
或者 第一種方式+第二種方式組合來加載 比如:
BundleConfig里面添加了一個
bundles.Add(new StyleBundle("~/Content1").Include("~/Content/common.css"));
組合調用 :@Styles.Render("~/Content1", "~/Content/site.css", "~/Content/content.css")
這時候頁面上會加載3個css文件
但是 如果BundleConfig里面這樣
bundles.Add(new StyleBundle("~/Content1").Include("~/Content/common.css","~/Content/content.css"));
頁面上這樣寫:@Styles.Render("~/Content1", "~/Content/site.css", "~/Content/content.css")
看到沒這個"~/Content/content.css"重復了, 2邊都引用了.. 這時候 程序不會再執行頁面上引用的css
注意:使用Bundle來引用css有個好處 就是可以把多個css文件在一起請求,瀏覽器只發一次請求 不過必須在Global.asax里面 加一段代碼 BundleTable.EnableOptimizations = true;
來啟用優化,看最終結果
而且 當頁面下次再次發送請求的時候 BundleConfig里面沒有更改的話 瀏覽器會從緩存中去取 ,這一點大大提高了性能 ...