您的位置:首页 > 编程语言 > ASP

ASP.NET MVC最佳实践(2)

2009-12-09 09:28 363 查看

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

默认情况下ASP.NET MVC会创建Content, Scripts文件夹来存放它们,但是我不喜欢这种方式。我喜欢以下的文件夹组织方式,它能够让我仅要为一个Assets文件夹设置静态文件缓存,而不是为多个文件夹分别设置:

Assets
+images
+scripts
+stylesheets
无论文件夹是按什么方式组织的,创建UrlHelper的扩展方法来映射这些文件夹,以便您能够在视图中很方便地引用它们,并且,将来如果您需要修改文件夹的结构,您也不必做大量的“查找/替换”。建议为那些在您的视图中经常引用到的资源创建扩展方法。。例如:

UrlHelper扩展

public static string Image(this UrlHelper helper, string fileName)
{
return helper.Content("~/assets/images/{0}".FormatWith(fileName));
}
public static string Stylesheet(this UrlHelper helper, string fileName)
{
return helper.Content("~/assets/stylesheets/{0}".FormatWith(fileName));
}

public static string NoIcon(this UrlHelper helper)
{
return Image(helper, "noIcon.png");
}


在引用这些资源时,您可以这样来引用:

<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" />
内容来自用户分享和网络整理,不保证内容的准确性,如有侵权内容,可联系管理员处理 点击这里给我发消息
标签: