@Styles.Render

1.@Styles.Render

在页面上可以用@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里面没有更改的话 浏览器会从缓存中去取 ,这一点大大提高了性能 ...

原文地址:https://www.cnblogs.com/wfy680/p/12347498.html