This is the third in a series of posts about things I found out while learning ASP.NET MVC. Today : Helpers.
Helpers are, as their name suggests, helpful things. If, for example, you want to add the current assembly version information into a page, you are likely to run into a problem or two. ASP.NET MVC doesn’t create code-behind pages for you to do this kind of useful operation in. Instead, you have to fall back to the old Classic ASP technique of coding directly into the view page. That is far from ideal. For one thing, the following code snippet doesn’t produce the correct reult directly from a page.
<%= System.Reflection.Assembly.GetExecutingAssembly().GetName().Version.ToString(); %>
My experience of that was that it would, if you were very luck, print “0.0.0.0” rather than the current version.
So, how did I achieve it? I created a helper. Basically a helper is a static class, containing static methods (including extension methods)
Here’s an example of my SiteWideHelper.cs file
using stuff; namespace Helpers { public class SiteWideHelpers { public static string SiteVersion() { return System.Reflection.Assembly.GetExecutingAssembly().GetName().Version.ToString(); } public static string CurrentController(this HtmlHelper helper) { return (string)helper.ViewContext.RouteData.Values["controller"]; } } }
The helper class contains one “vanilla” method and one extension method to the HtmlHelper class. The first method, SiteVersion, simply treturns a string of the current assembly version. The second method, CurrentController, returns the name of the current controller by querying the extended HtmlHelper class.
Both of these methods may now be called, and their output rendered directly to the page. (Actually, I use the Currentcontroller method to determine which bits of sub-navigation are displayed on the master page.
<span>Web site version: <%= Html.Encode(SiteWideHelpers.SiteVersion()) %></span>
Don’t forget, instead of haveing to reference the fully qualified name of your method / class, you can import the namespace into your view
<%@ Import Namespace="Helpers" %>
I’m sure I’m missing some concepts here that would make development so much simpler, but for astarting point, this is working for me
One thought on “ASP.NET MVC – Helpers”
Comments are closed.