一、引言
在做网站是经常要对样式或者脚本进行更新,每次更新后需要客户端强制刷新才可以看到更新后的样式,或在样式文件应用处加版本号区分,
(常用的写法如“~/content/css/globe.css?v1.0”),还需要对每个引用 globe.css 文件的位置加版本号区分,工作量巨大。
所以,提供一个统一管理方案非常必要。
二、使用include.cofig 配置文件管理站点的所有 css 和 js 引用
命名规则:如果加入的是 css 文件 ,key 必须以 css_ 开头;如果是 js 文件 ,key 必须以 js_ 开头;
实例如下:
<?xml version="1.0"?> <configuration><system.web><compilation debug="true" targetFramework="4.0" /></system.web><appSettings><add key="css_css1" value="~/views/Center/css1.cshtml"/><add key="js_js1" value="~/views/Center/js1.cshtml"/></appSettings> </configuration>
三、封装读取方法
using System; using System.Configuration; using System.IO; using System.Text; using System.Web; using System.Web.Mvc; using System.Linq; namespace DiscussCenter.Ctrl.Utility { /// <summary> /// Html 对象扩展类 /// </summary> public static class WebExtension { /// <summary> /// 导入Css文件 /// </summary> /// <param name="url"></param> /// <param name="cssName">样式名</param> /// <returns></returns> public static MvcHtmlString IncludeCss(this UrlHelper url,params string[] cssName) { StringBuilder str = new StringBuilder(); foreach (string css in cssName) { str.Append( string.Format("<link type=\"text/css\" rel=\"stylesheet\" href=\"{0}\"/>" , url.Content(GetIncludeSettingValue("css_"+css)))); } return new MvcHtmlString(str.ToString()); } /// <summary> /// 导入Js文件 /// </summary> /// <param name="url"></param> /// <param name="cssName">脚本文件名</param> /// <returns></returns> public static MvcHtmlString IncludeJs(this UrlHelper url, params string[] jsName) { StringBuilder str = new StringBuilder(); foreach (string js in jsName) { str.Append( string.Format("<script type=\"text/javascript\" src=\"{0}\" ></script>" ,url.Content(GetIncludeSettingValue("js_" + js)))); } return new MvcHtmlString(str.ToString()); } /// <summary> /// 获取自定义 Include.config 文件中的 appsetting 节点值 /// </summary> /// <param name="key">节点名称</param> /// <returns></returns> public static string GetIncludeSettingValue(string key) { string indexConfigPath = Path.Combine(HttpContext.Current.Request.PhysicalApplicationPath, "Include.Config"); if (!File.Exists(indexConfigPath)) throw new Exception(string.Format("缺少 Include.Config 配置文件:{0}", indexConfigPath)); ExeConfigurationFileMap ecf = new ExeConfigurationFileMap(); ecf.ExeConfigFilename = indexConfigPath; Configuration config = ConfigurationManager.OpenMappedExeConfiguration(ecf, ConfigurationUserLevel.None); if (!config.AppSettings.Settings.AllKeys.Contains(key)) throw new Exception(string.Format("Include.Config 配置文件,缺少必要的配置节 {0}", key)); return config.AppSettings.Settings[key].Value; } } }
四、页面调用
注意:需要引用扩展方法的命名空间
@using DiscussCenter.Ctrl.Utility;
@Url.IncludeCss("css1", "css100") //引用样式文件
@Url.IncludeJs("js1") //引用 脚本文件
草青工作室:http://blog.csdn.net/xxj_jing
原文地址:(http://blog.csdn.net/xxj_jing/article/details/8556780)
转载于:https://www.cnblogs.com/xxj-jing/archive/2013/01/16/2890038.html
相关资源:各显卡算力对照表!