Subscribe to Windows IT Pro
January 25, 2011 04:00 PM

User Controls and HTML Helpers

Learn how ASP.NET MVC helpers are a better solution for reusing chunks of HTML markup
Dev Pro
InstantDoc ID #129142
Rating: (5)

If you introduce ASP.NET MVC to developers with a strong ASP.NET Web Forms expertise, they feel suddenly out of place because they can’t use server controls (at least, not with the same ease and comfort). Therefore, one of the first questions asked is "What alternate tools does ASP.NET MVC offer to create reusable pieces of markup to display in the browser?" All in all, you have two non-exclusive choices in ASP.NET MVC. You can use classic user controls (ASCX files) or HTML helpers.

You can successfully employ either approach to define layout and content of ASP.NET MVC views. But neither approach is perfect; both have pros and cons. With HTML helpers, you have to build any HTML markup you need using C# code. Most developers with ASP.NET expertise will find this difficult and will prefer taking a more traditional approach, such as using user controls. For rendering complex layouts, however, user controls are problematic in ASP.NET MVC. So the question is: "Is there a middle ground that allows developers to use the familiar HTML pattern while filling up views with HTML helpers?"

HTML Helpers

An HTML helper is an extension method attached to the HtmlHelper class. From within an ASP.NET MVC view you use an HTML helper through the Html property of the ViewPage class. The main purpose of any HTML helper is to act as a simple factory of HTML markup. Put another way, all an HTML helper does is prepare and emit HTML in the form of a string. Here’s how you use an HTML helper to emit all the markup required for an input tag:

<%= Html.TextBox("LastName") %>

The method TextBox extends the HtmlHelper class to add the capability of emitting a piece of HTML that renders as an <input> element. Here’s the internal structure of an HTML helper:

 

public static MvcHtmlString TextBox(this HtmlHelper htmlHelper, string name)
{
    var builder = new StringBuilder();
    // Accumulate HTML text into the string-builder object
    :
    return MvcHtmlString.Create(builder.ToString());
}

Related Content:

ARTICLE TOOLS

Comments
  • Best
    1 year ago
    Jan 27, 2011

    Great topic for an article!! Thanks Dino! More articles on custom controls and paypal helpers for MVC would be great. Cheers.

You must log on before posting a comment.

Are you a new visitor? Register Here

advertisement

advertisement

Windows is a trademark of the Microsoft group of companies. Windows IT Pro is used by Penton Media Inc. under license from owner.