(转)ASP.NET MVC最佳实践(2)

原文地址:http://space.itpub.net/740297/viewspace-588774

 

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

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

 

posted on 2010-11-02 13:52  黑子范  阅读(268)  评论(0)    收藏  举报

导航