Keeping busy with ASP.NET MVC

I’m looking for a job in “the worst recession since the great depression” blah blah blah. It really sucks.

To keep busy, I’ve been doing some ‘freelance’ work. I’ve been trying to expand more into MVC products by deploying a RadiantCMS site in Ruby on Rails and an e-business site I’m developing in ASP.NET MVC.

I’m liking the entire MVC mantra of keeping it DRY, or Don’t Repeat Yourself. I don’t know if it’s because I’ve always hated repeating myself and this idea really hits home with me, or if it’s just because it’s a huge change from what I’ve encountered professionally and academically. Whatever it is, I love it.

One thing I love about ASP.NET MVC is it’s heavy use of extension methods as “Helpers”. It’s easy to go overboard with helpers, but I like them anyway. One nice thing about them is that if you are like me, and sometimes forget to close some HTML tags, helpers can fix that.

For instance, if you’re always writing div tags and adding id and class attributes, you can standardize the procedure with the following two methods (I overloaded them to accept objects just as ASP.NET MVC does):

/// <summary>
  /// Returns a DIV with specified attributes
  /// </summary>
  /// <param name="helper">HtmlHelper class to extend</param>
  /// <param name="contents">Contents of the DIV element</param>
  /// <param name="htmlAttributes">Attributes to apply to the DIV element</param>
  /// <returns>string</returns>
  public static string Div(this HtmlHelper helper, string contents, object htmlAttributes)
  {
       return Div(helper, contents, new RouteValueDictionary(htmlAttributes));
   }

   /// <summary>
   /// Returns a DIV with specified attributes
   /// </summary>
   /// <param name="helper">HtmlHelper class to extend</param>
   /// <param name="contents">Contents of the DIV elemtn</param>
   /// <returns>string</returns>
   public static string Div(this HtmlHelper helper, string contents, 
       IDictionary<string, object> htmlAttributes)
   {
       TagBuilder tagBuilder = new TagBuilder("div")
       {
            InnerHtml = contents.NewlineToHtmlBreak() ?? string.Empty
       };

       if(htmlAttributes != null)
       {
           tagBuilder.MergeAttributes(htmlAttributes);
       }

       return tagBuilder.ToString();
   }

this allows you to do the following in a View:

1:  <%= Html.Div("<p>This is content in left_box and helper method</p>", new {@class="left_box"}) %>

You could, of course, call the methods Tag and pass in the string value of the tag to create, eg. a, div, p, em, etc. Then, you would have a fairly generic helper to standardize all of your tags!

Even the NewlineToHtmlBreak method on String class is an extension method which calls

String.Replace(Environment.Newline, "<br />"

on the string input. I’ve done this because it’s easier/faster to rely on Intellisense to hit .n+TAB than to type out the entire method. Like I said, it is very easy to go overboard with Helpers!