ASP.NET MVC Helper for creating Twitter Bootstrap Form Fields

Being a good (read: lazy) programmer, when I find myself doing something over and over, I automate it. Ostensibly, this is done to save time in the long run and to prevent mistakes in repetitive work. Really though, it’s because I think doing the same thing is boring, and creating something new is fun.

One thing I got sick of recently was creating form fields for Twitter Bootstrap forms. It’s not a large or complex task, and neither is the solution. It will help reduce the number of lines in your Razor files though. If you have improvements, let me know!

  1. namespace MySweetApp
  2. {
  3.   using System;
  4.   using System.Linq.Expressions;
  5.   using System.Text;
  6.   using System.Web;
  7.   using System.Web.Mvc;
  8.   using System.Web.Mvc.Html;
  10.   public static class FormHelpers
  11.   {
  12.     public static HtmlString FormField(this HtmlHelper helper, Expression<Func> func)
  13.     {
  14.       var result = new StringBuilder();
  15.       result.Append(@"<div>");
  16.       result.Append(helper.LabelFor(func, new { @class = "control-label" }));
  17.       result.Append(@"<div>");
  18.       result.Append(helper.EditorFor(func));
  19.       result.Append(@"</div></div>");
  20.       return new HtmlString(result.ToString());
  21.     }
  22.   }
  23. }

Also, is there a good site out there for sharing code snippets? I haven’t found one. I don’t want to publish small things like this on GitHub or NuGet, but I would like to get them somewhere that’s more searchable than my blog, where they might have a chance of helping more people.

Posted Wednesday, May 8th, 2013 under ASP.NET MVC.

Leave a Reply