Dot Net Stuff

Understanding HTML Helpers in ASP.NET MVC Framework.


One of the most important purpose of server controls in ASP.NET —favoring HTMLlevel code reuse. ASP.NET MVC doesn’t have the server controls but it have. To achieve these features in MVC, It needs be built programmatically based on dynamically discovered data. What’s a technology equivalent to server? controls in ASP.NET MVC? Here comes the sense of HTML helpers.

HTML helpers certainly are not the same as server controls, but they are the closest you can get to HTML-level code reuse with a view engine. An HTML helper method has no view state, no postbacks, and no page life cycle and events. HTML helpers are simple HTML factories. Technically, an HTML helper is an extension method defined on a system class—the HtmlHelper class—that outputs an HTML string based on the provided input data. Internally, in fact, an HTML helper simply accumulates text into a StringBuilder object.


HTML helpers can be classified into three categories.

1. Basic HTML Helpers

ASP.NET MVC framework has some HTML helpers for ready to use. Following are the list of basic HTML Helpers.


HTML Helpers
Methods Type Description
BeginForm, BeginRouteForm From It Returns an internal object that represents an HTML form which system uses to render the <form> tag
EndForm From A void method, closes the pending </form > tag
CheckBox, CheckBoxFor Input Returns the HTML string for a check box input element
Hidden, HiddenFor Input Returns the HTML string for a hidden input element/td>
Password, PasswordFor Input Returns the HTML string for a password input element
RadioButton, RadioButtonFor Input Returns the HTML string for a radio button input element
TextBox, TextBoxFor Input Returns the HTML string for a text input element
Label, LabelFor Input Returns the HTML string for an HTML label element
ActionLink, RouteLink Link Returns the HTML string for an HTML link
DropDownList, DropDownListFor List Returns the HTML string for a drop-down list
ListBox, ListboxFor List Returns the HTML string for a list box
TextArea, TextAreaFor TextArea Returns the HTML string for a text area
Partial Partial Returns the HTML string incorporated in the specified user control
RenderPartial Partial Writes the HTML string incorporated in the specified user control to the output stream
ValidationMessage, ValidationMessageFor Validation Returns the HTML string for a validation message
ValidationSummary Validation Returns the HTML string for a validation summary message

As an example, let’s see how to use an HTML helper to create a text box with programmatically determined text. You place the call in a code block if you’re using the ASPX view engine:


<%: Html.TextBox("TextBox1", ViewBag.DefaultText) %>

Or you prefix the call with the @ symbol if you’re using Razor. (I’ll say more about Razor in a moment.)


@Html.TextBox("TextBox1", ViewBag.DefaultText)

2. Templated HTML Helpers:

Templated HTML helpers aim to make the display and editing of data quick to write and independent from too many HTML and CSS details How would you display or edit this data?

Writing HTML forms over and over again leads to repetitive, boring, and therefore error-prone code. Templated helpers take an object, read the value of properties, and decide how to best render those values. By decorating the view-model objects with special attributes, you provide the helper further guidance regarding user-interface hints and validation.

With templated helpers, you are not losing control over the user interface; more simply, attributes in the model establish a number of conventions and save you from a number of repetitive tasks.

Templated helpers actually come with three overloads. Using the Display helper as an example, you have the following more specific helpers: Display, DisplayFor, and DisplayForModel. There’s no functional difference between Display, DisplayFor, and DisplayForModel. They differ only in terms of the input parameters they can manage. There are another flavor for each Display helpers known as Editor helpers Examples:

The Display helper accepts a string indicating the name of the property in the ViewData dictionary, or on the view-model object, to be processed:


<%= Html.Display("FirstName") %>

The Editor helper for above Display can be write as


<%= Html.EditorFor(person => person.FirstName) %>

The DisplayFor helper accepts a lambda expression and requires that a view-model object be passed to the view:


<%= Html.DisplayFor(model => model.FirstName) %>

Finally, DisplayForModel is a shortcut for DisplayFor getting the expression model => model:


<%= Html.DisplayForModel() %>

3. Custom Helpers

The native set of HTML helper methods is definitely a great help, but it’s probably insufficient for many real-world applications. Native helpers, in fact, cover only the markup of basic HTML elements. In this regard, HTML helpers are significantly different from server controls because they completely lack abstraction over HTML. Extending the set of HTML helpers is easy, however. All that is required is an extension method for the HtmlHelper class or for the AjaxHelper class if you’re interested in creating an HTML factory that does some Ajax work.

The helper has up to four parameters, three of which are optional parameters. It takes the original text and its null replacement, plus a format string to embellish the text in both cases.


public static class OptionalTextHelpers
{
public static MvcHtmlString OptionalText(this HtmlHelper helper,
String text,
String format="{0}",
String alternateText="",
String alternateFormat="{0}")
{
var actualText = text;
var actualFormat = format;
if (String.IsNullOrEmpty(actualText))
{
actualText = alternateText;
actualFormat = alternateFormat;
}
return MvcHtmlString.Create(String.Format(actualFormat, actualText));
}
}


Keen to hear from you...!

If you have any questions related to what's mentioned in the article or need help with any issue, ask it, I would love to here from you. Please MakeUseOf Contact and i will be more than happy to help.

About the author

Anil Sharma is Chief Editor of dotnet-stuff.com. He's a software professional and loves to work with Microsoft .Net. He's usually writes articles about .Net related technologies and here to shares his experiences, personal notes, Tutorials, Examples, Problems & Solutions, Code Snippets, Reference Manual and Resources with C#, Asp.Net, Linq , Ajax, MVC, Entity Framework, WCF, SQL Server, jQuery, Visual Studio and much more...!!!

Loading