When you have a website with a lot of static content: images, Javascript, CSS, etc… you will find yourself constantly typing out the same path information with the exception of the name of the actual file. Creating a class extension to the UrlHelper can help greatly reduce your development efforts with a few simple additions.
Using the Url.Content
If you are not already doing so, you should start using the UrlHelper to include static content. For example, your CSS file should be loaded as follows:
[code]
<link href=”@Url.Content(“~/Content/Site.css”)” rel=”stylesheet” type=”text/css” />
[/code]
The UrlHelper makes it easy to include files without the need to specify an absolute or relative path, allowing your code to exist inside of a sub folder.
Like your CSS files, your images should be referenced in a similar fashion to:
[code]
<img src=”@Url.Content(“~/Content/Images/title.png”)” alt=”” />
[/code]
Creating your own UrlHelper Extension
Now, if all of your images exist inside of the Content/Images folder, it could save a lot of time if you simplified your code as follows:
[code]
<img src=”@Url.Image(“title.png”)” alt=”” />
[/code]
Each time you create an image, there is a lot less typing to do. Furthermore, if you ever decided to move your images to a different directly, it will be as simple as changing one line of code.
To accomplish the above example, you will need to create an extension class to the UrlHelper class built-in to the MVC namespace. To complete this example, I would suggest creating a new folder called Helpers, assuming you do not already have one, in your project to help keep your code organized. Then inside this folder, create a new class called UrlHelperExtension.
[code]
using System;
using System.Web.Mvc;
namespace MvcApplication.Helpers
{
public static class UrlHelperExtension
{
public static string Image(this UrlHelper helper, string imageName)
{
return helper.Content(“~/Content/Images/” + imageName);
}
}
}
[/code]
In the above code, this UrlHelper helper, is the first parameter in the function and the imageName is second; however, if you recall in the previous example, we only passed one parameter. This is the beauty of extension classes. The compiler translates the code into a call on the static method.
To complete this example off, you must ensure that you manually include a using directive in your MVC views to the helper class to ensure it’s available on the view:
[code]
@using MvcApplication.Helpers;
// .. your other html/razor code
<img src=”@Url.Image(“title.png”)” alt=”” />
// .. your other html/razor code
[/code]
Summary of the UrlHelper Extension
By extending built-in ASP.NET classes you can easily add new helper functions that leverage existing functions of that class. Extensions should be used sparingly and typically for simple add-ons like the above example. For more complex examples, the classes mostly likely should be inherited instead of extended.