ASP.NET MVC最佳实践(2)

2.创建UrlHelper的扩展方法(extension method)来映射您的JavaScript, Stylesheet以及Image文件夹

默认情况下ASP.NET MVC会创建Content, Scripts文件夹来存放它们,但是我不喜欢这种方式。我喜欢以下的文件夹组织方式,它能够让我仅要为一个Assets文件夹设置静态文件缓存,而不是为多个文件夹分别设置:
Assets 
+images 
+scripts 
+stylesheets
无论文件夹是按什么方式组织的,创建UrlHelper的扩展方法来映射这些文件夹,以便您能够在视图中很方便地引用它们,并且,将来如果您需要修改文件夹的结构,您也不必做大量的“查找/替换”。建议为那些在您的视图中经常引用到的资源创建扩展方法。。例如:
ContractedBlock.gif ExpandedBlockStart.gif UrlHelper扩展
 
       
1 public static string Image( this UrlHelper helper, string fileName)
2 {
3 return helper.Content( " ~/assets/images/{0} " .FormatWith(fileName));
4 }
5   public static string Stylesheet( this UrlHelper helper, string fileName)
6 {
7 return helper.Content( " ~/assets/stylesheets/{0} " .FormatWith(fileName));
8 }
9
10   public static string NoIcon( this UrlHelper helper)
11 {
12 return Image(helper, " noIcon.png " );
13 }
 
在引用这些资源时,您可以这样来引用:
 
      
< link href ="<%= Url.Stylesheet(" site.css")% > " rel="stylesheet" type="text/css"/>
  
而不是默认的这样:
 
      
< link href ="http://www.cnblogs.com/Content/Site.css" rel ="stylesheet" type ="text/css" />
  

转载于:https://www.cnblogs.com/200831856/archive/2009/12/09/ASP-NET-MVC-UrlHelper-KuoZhan-02.html

猜你喜欢

转载自blog.csdn.net/weixin_33767813/article/details/93711401
今日推荐