ASP.Net MVC Helper Functions

ASP.Net MVC has some great helper functions for building forms, input elements, and links. Here is an example of the helper function that creates a hyperlink to the Index action on the Guest controller.

 

<%= Html.ActionLink("Back", "Index", "Guest")%>

 

This is a great way to create links that persist changes to your site's URL routing.

I am now working on an ASP.Net MVC application for the Ronald McDonald House of Iowa. I quickly made a discovery that I needed some additional helper functions. The first problem I ran into was the relative paths to the CSS files in my site. I discovered that as the URL scheme had varying numbers of parameters, the relative path to the CSS changed. I needed a helper function to create the proper relative path. So, I created the following helper function to do just that. Basically, what I wanted to do is something like this:

 

<%= Html.Css("~/Content/Site.css") %>

 

I quickly discovered the same problem with JavaScript files and Images. So, I made the following helper functions. Here is the code for the helper functions.

   public static class HtmlHelperExentsions
   {
       public static string Script(this HtmlHelper html, string path)
       {
           var filePath = VirtualPathUtility.ToAbsolute(path);
           return "<script type=\"text/javascript\" src=\"" + filePath + "\"></script>";
       }
       public static string Image(this HtmlHelper html, string path,
           string alt, string css, string style)
       {
           var filePath = VirtualPathUtility.ToAbsolute(path);
           return "<img src=\"" + filePath + "\" title=\"" + alt + " class=\"" + css + "\" style = \"" + style + "\" />";
       }
       public static string Image(this HtmlHelper html, string path,
           string alt)
       {
           return Image(html, path, alt, "", "");
       }
       public static string Css(this HtmlHelper html, string path)
       {
           var filePath = VirtualPathUtility.ToAbsolute(path);
           return "<link href=\""+filePath+"\" rel=\"stylesheet\" type=\"text/css\" />";
       }
   }

These functions seem to be working well for me, I hope they help you out as well. This code is released under the MIT license.