Helpers for the MS MVC Framework

Go to the bottom of this post for the download.

There's a discussion going on at the MvcContrib site about including UI Helpers in the MvcContrib project. The discussion seems to be centralising around the issue of whether helpers should be implemented through extension methods (the approach the MVCToolkit takes), regular static methods or instance methods.

My preference is for instance methods on dedicated helper classes. This approach is the most flexible as it allows you to:

  • Replace an entire helper with a custom implementation
  • Easily share services between all helpers

I decided to put together a sample application that uses an IoC container (Windsor) for creating helpers. The sample project includes:

  • FormHelper and UrlHelper implementations that are created using the MvcContrib DependencyResolver.
  • Services for generating URLs (IUrlBuilder) and for automatic data binding (IDataBinder)
  • Delegate-based rendering (see this post on Adam Tybor's blog for more info).
  • Using IDictionaries for specifying HTML attributes
  • Methods for generating text fields, text areas, hidden fields, forms and hyperlinks

Some sample code:

<% Form.For("person", new Hash(action => "Save"), form => { %>
	Surname: <%= form.TextField("Surname", new Hash(style => "width: 200px")) %>
	<br />
	Forename: <%= form.TextField("Forename", new Hash(style => "width: 200px"))%>
	<br /><br />
	<%= form.HiddenField("id") %>
	<%= form.Submit() %>
<% }); %>

Which generates...

<form method="post" action="/Home/Save">
	Surname: <input type="text" id="person_Surname" name="person.Surname" value="Smith" style="width: 200px" />
	<br />
	Forename: <input type="text" id="person_Forename" name="person.Forename" value="Jane" style="width: 200px" />
	<br /><br />
	<input type="hidden" id="person_id" name="" value="2" />
	<input type="submit" value="Submit" />

Note: To run the sample you will need the .NET 3.5 Extensions CTP installed.


  • The DefaultDataBinder implementation uses code from Castle's MonoRail
  • The DefaultUrlBuilder uses code from Rob Conery's MvcToolkit
  • The Hash class is inspired by this post on Bill Pierce's blog.

The download can be found here.

Written on February 2, 2008