ASP.NET MVC Extension Methods of UrlHelper
I think this is kind of obvious, but I guess it might not be for everyone because I’ve seen some code where people do not use this! URL Helpers are really easy to setup, it takes only a few minutes and will probably save you a lot of massive Search & Replace in the future!
public static string Image(this UrlHelper helper, string fileName)
{
return helper.Content("~/Content/Images/" + fileName));
}
public static string Stylesheet(this UrlHelper helper, string fileName)
{
return helper.Content("~/Content/Stylesheets/" + fileName);
}
public static string Script(this UrlHelper helper, string fileName)
{
return helper.Content("~/Content/Scripts/" + fileName);
}
So instead of doing this:
<link href="../../../Content/StyleSheets/Main.css" rel="stylesheet" type="text/css" />
You can do this:
<link href="<%= Url.Stylesheet("Main.css")%>" rel="stylesheet" type="text/css" />
These are just 3 common examples, you should do the same thing for things you use a lot.
This entry was posted on Monday, September 21st, 2009 at 9:31 pm and is filed under ASP.NET, MVC. You can follow any responses to this entry through the RSS 2.0 feed. You can leave a response, or trackback from your own site.


Jeff Fritz September 22nd, 2009 at 10:28 am
Personally, I like to add UrlHelper extensions for some of my more commonly used routes.. it helps to clarify my ASPX code