Ryan Lundy
Ryan Lundy

Reputation: 210090

Closer to the HTML...then why the HtmlHelper?

I often see, touted as one of the big benefits of ASP.NET MVC, the fact that it gets you closer to the actual page markup, as opposed to the pseudomarkup of WebForms.

If that's the case, then why does the HtmlHelper exist? It seems like all this LabelFor, TextBoxFor stuff is just as much pseudomarkup as <asp:Label> and <asp:TextBox> are in WebForms.

What am I missing? Why is there an HtmlHelper class? Do people use it in real life?

Upvotes: 1

Views: 188

Answers (4)

stoic
stoic

Reputation: 4830

I don't quite agree with the answers, and i somehow agree with you.

You can think of the helpers as pre-built custom controls, if you want to have some code generated you can make use of the helpers, if you want a clean approach and get closer to the html then don't.

The important point here is that MVC allows you to get close to the html, but does not limit you to only that.

You can create your own helper that created the markup you wish, and use that instead.

At the end of the day, it comes down to your own preference, and you can choose to or choose not to be closer to the html

Upvotes: 1

GregL
GregL

Reputation: 38103

Whilst you are right in saying that HtmlHelper functions do abstract away the exact markup rendered, the big advantage of this is that the views are more DRY and you are able to pass in the necessary parameters to the functions in order to customise the HTML generated.

Rather than having to manually type out a full <input /> tag, complete with value=<%= Model.Property %>, Html.TextBoxFor is a more concise way of outputting the same thing. And as with all DRY approaches, if you need to change the HTML for all textboxes in your application (e.g. to output a new attribute) all you need to do is change the HtmlHelper method.

They seem to me a little like simple, lightweight partial views that are just designed to output some consistent HTML given some input.

Upvotes: 3

Daniel A. White
Daniel A. White

Reputation: 190897

It simplifies the creation of those and allows them to be strongly named. Of course people use this!

Upvotes: 1

SLaks
SLaks

Reputation: 887225

The point of HTML helpers is to eliminate tedious and repetitive <input> tags.

Unlike server-side controls, HTML helpers emit raw, (fairly-)predictable HTML.

Upvotes: 2

Related Questions