Friday, September 13, 2013

ASP.NET MVC Extensions


MVC Extensions (Helpers) abstracts HTML code from the developers so that they can focus on the UI layout. It helps developers by providing an easy way to render HTML and from tedious work of writing HTML tags. It also reduces code duplication. Further it provides traditional ASP.NET Web Form controls’ look and feel, thereby making Web Form developers feel home and allowing them an easy transition for the Web Form developers into MVC developers.
In this blog I will give a brief introduction of the MVC Extensions and how to create a custom Extension. In my next blog I will show an elegant way of creating a custom Extensions using which a complex HTML Helper can be efficiently created and seamlessly integrated.

Framework Extensions
ASP.NET MVC framework provides several helper methods to facilitate easy rendering of form elements. The below list shows the HTML helpers provided by the framework:
  • ActionLink — Links to an action method.
  • BeginForm — Marks the start of a form and links to the action method that renders the form.
  • CheckBox — Renders a check box.
  • DropDownList — Renders a drop-down list.
  • Hidden — Embeds information in the form that is not rendered for the user to see.
  • ListBox — Renders a list box.
  • Password — Renders a text box for entering a password.
  • RadioButton — Renders a radio button.
  • TextArea — Renders a text area (multi-line text box).
  • TextBox — Renders a text box.
Refer to the below msdn link for more information on the available helpers and details on how to use the frequent MVC helpers


Custom Extensions
An HTML Helper is an extension method that returns a string. The framework provides necessary infrastructure to create custom helpers in an effortless way. The below link demonstrates on how to create a custom HTML Helper.

http://www.asp.net/mvc/tutorials/older-versions/views/creating-custom-html-helpers-cs

The above link shows an example of creating a simple Label Helper. Below is the code extracted from there:

using System;
using System.Web.Mvc;
 
namespace MvcApplication1.Helpers
{
  public static class LabelExtensions
  {
    public static string Label(this HtmlHelper helper, string target, string txt)
    {
      return String.Format("<label for='{0}'>{1}</label>", target, txt);
    }
  }
}
This Label extension is used in the View as follows:
       @Html.Label("firstName", "First Name:")


As you see the Label Extension takes all the necessary parameters as function inputs. The parameter injection is good way if you have limited number of parameters. This approach will quickly become ugly if you have many parameters with some optional parameters. If you are building a complex HTML Extensions this is clearly not the way to go.

In my next blog I will show how to create complex HTML Helpers using the Fluent interface which would not only reduces the complexity but also increases code readability.

No comments:

Post a Comment