Let’s first create a new class library project in Visual Studio 2010. I just name it HelperLibrary. Within the project delete the class that was generated by the Visual Studio template and create a new class named FavoriteHelper. Make the class public and static. Before we can write our methods, we need to import the following two DLLs:
In the class insert a static method named AddToFavorites with the following signature:
public static HelperResult AddToFavorites(string text)
return new HelperResult(tw => tw.Write(
"\" onDragstart=\"return false\" "+
The method accepts a string parameter, whose text will later be shown on the web page. It returns an object of type HelperResult which can be interpreted by the Razor Engine. The HelperResult class is contained within the System.Web.WebPages assembly and accepts a TextWriter in its constructor.
Alternatively you could use the following method:
public static IHtmlString AddFavorite(string text)
return new HtmlString("<a href=\":" +
"\" onDragstart=\"return false\" " +
location.href, document.title);return false'>" +
text + "</a>");
In that case you won’t need the System.Web.WebPages.dll. It’s also a little bit easier, because you don’t have to use an additional TextWriter.
After we have inserted our methods, we need to build the library and integrate it into our WebMatrix project. Before compiling the assembly, check the settings and make sure the correct framework version is used. In order to use Razor, you have to target at least .NET Framework 4.0. After building the assembly we can just copy it to the bin folder of our web application project, hit refresh within WebMatrix and insert the call to our helper method on any web page:
@HelperLibrary.Favorites.AddToFavorites("Add to favorites!")
Pay attention to use the full namespace declaration. Otherwise the method won’t be found.
If you start the page, you will see a link on it to add this page to your favorites:
A test by clicking on it reveals that it works: