Html Helpers and Extension Methods

Stephen Walther has a good blog post on Creating New HTML Helper with Extension Methods

This is one area of MVC that is very flexible and easy to use.  HTML helpers in MVC are a great example of putting extension methods to good use.

One comment – he shows where he imports the namespace at the top.  Alternatively you can include the reference in the web.config and then not need to reference it on every page.  With this in mind, consolidating Html helpers into a single assembly for your application would highly benefit from this approach

In the ‘pages’ section of the web.config:

      <namespaces>
        <add namespace="System.Web.Mvc"/>
        <add namespace="System.Web.Routing"/>
        <add namespace="System.Linq"/>
        <add namespace="System.Collections.Generic"/>
        <add namespace="Bistro.Utils"/>   <!-- my utility class used for extensions -->
      </namespaces>

More links:

 

Drew Miller  on ‘how to create a html helper for asp.net mvc’  (one correction I see for preview 3 – instead of _class, use @class)

“The steps to create an HTML helper are [3]:

  1. Create a static class to put the HTML helper methods into
  2. Create an extension method for HtmlHelper (that means the first parameter must be “this HtmlHelper”)
  3. Return the HTML to render from the method “

Phil Haacked – code based repeater example

AzamSharp - a TextBox extension that sets up an onclick event
Maarten Balliauw - A custom ActionResult - ImageResult 'ImageResultHelper' (this one is pretty cool!)
Well, that is a good start, I'm sure there are more out there - but it does show how easy it is to extend the html helpers in asp.net mvc!
Advertisements

Leave a Reply

Fill in your details below or click an icon to log in:

WordPress.com Logo

You are commenting using your WordPress.com account. Log Out / Change )

Twitter picture

You are commenting using your Twitter account. Log Out / Change )

Facebook photo

You are commenting using your Facebook account. Log Out / Change )

Google+ photo

You are commenting using your Google+ account. Log Out / Change )

Connecting to %s