« Home | Credit Card Expiration Date DropDownList Sample Code » | Visual Studio Automatically Changing the IDs in So... » | Better Perfomance of Web Applications » | Display Numerals in Arabic Format » | The Controls collection cannot be modified because... » | Team Foundation PowerToys » | String is All Lower or All Upper Case » | Detecting Chrome browser in ASP.NET » | Chart Control for .net 3.5 » | Increase the VS screen for HTML pages »

Handy Extension Methods for ASP.NET MVC's UrlHelper

Mickael Chambaud posted three extension methods he created for UrlHelper: Image(), Stylesheet() and Script(). They make it pretty easy to keep your images, stylesheets and scripts organized in a single location – without the need for you to remember where they are placed. And if you need to move things around for some reason, you only have to change the extension methods.

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="<%= UrlHelper.Stylesheet("Main.css")%>" rel="stylesheet" type="text/css" />


Happy Coding...

Labels: , , , , , ,

Post a Comment