开发者

Tool / accelerator for improving adding css and script resources to MVC3 Razor pages

Is there any tool to make adding files to MVC3 razor pages faster?

I find myself having to drag script files onto the page to generate:

<s开发者_运维知识库cript src="../../Scripts/rails.js" type="text/javascript"></script>

Which then i'll copy and paste

<script src="@Url.Content("~/Scripts/")" type="text/javascript"></script>

Then cut/drag the rails.js fragment into the new script statement. Then at some point after this hopefully I remember I need to clean up a whole bunch of duplicated and/or broken script links.

There has to be a better way than this that doesn't involve typing urls out manually.


Came across this blog post earlier today and ASP.NET MVC Best Practices (Part 1) and it's guidance shows

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");
}

This seems like the optimal solution if you use a good layout scheme for your resources.

Edit: FWIW

public static string FormatWith(this string format, params object[] inputs)
{
    return string.Format(format, inputs)
}


You can use T4MVC to get a compile-time validation your your links.

2.3. Strongly typed links to script files and static resources

T4MVC generates static helpers for your content files and script files. So instead of writing:

<img src="/Content/nerd.jpg" /> 

You can write:

<img src="<%= Links.Content.nerd_jpg %>" /> 

Likewise, instead of

<script src="/Scripts/Map.js" type="text/javascript"></script> 

You can write

<script src="<%= Links.Scripts.Map_js %>" type="text/javascript"></script>

The obvious benefit is that you’ll get a compile error if you ever move or rename your static resource, so you’ll catch it earlier.

Another benefit is that you get a more versatile reference. When you write src="/Content/nerd.jpg", your app will only work when it’s deployed at the root of the site. But when you use the helper, it executes some server side logic that makes sure your reference is correct wherever your site is rooted. It does this by calling VirtualPathUtility.ToAbsolute("~/Content/nerd.jpg").

0

上一篇:

下一篇:

精彩评论

暂无评论...
验证码 换一张
取 消

最新问答

问答排行榜