Custom HTML "Widgets" for ASP.NET MVC3

I was experimenting with ASP.NET MVC3 and found myself in need of some HTML outputted by the Razor engine that would need to be used many times. I wanted to follow the DRY (Don't Repeat Yourself) principle by having the HTML appear in one spot and allow me to use it many times. Ideally I wanted something like the builtin HTML "widgets".

   @Html.DropDownList("DropDownID", Model.Items)

The way I accomplished this was extension methods. Extension methods are an interesting way to add functionality to a class without inheritence. There are drawbacks, such as not being able to access protected members of the base class, but for some cases this is ok.

I decided to use extension methods to add a method to the class that corresponded to the @Html object in the Razor engine. I found out that this class was the HtmlHelper class in the System.Web.Mvc namespace. By extending the HtmlHelper class via extension methods, I was able to achieve my goal of adding a custom widget.

namespace MvcHtml
{
   using System.Web.Mvc;

   public static class ExtensionHtml
   {
      public static MvcHtmlString CustomWidget(this HtmlHelper htmlHelper, string property)
      {
         TagBuilder tagBuilder = new TagBuilder("div");
         tagBuilder.SetInnerText(property);
         return new MvcHtmlString(tagBuilder.ToString());
      }
   }
}

After this little bit of work, we are ready to use the custom widget in our view template just as traditional widgets provided for us.

   @Html.CustomWidget("SampleProperty")

I hope this helps people understand how Razor is producing HTML from these view files!

2 comments:

K Siva Karthikeyan said...

How about adding content to the widget?

Unknown said...

@K siva Karthikeyan
What do you mean by content? You can make the response of the function whatever html you want. You don't even have to use the tag builder if you don't want to.