views:

99

answers:

2

Does anybody know why could some HTML form controls be rendered using System.Web.Mvc.HtmlHelper (hidden, checkbox, password, textbox) and some couldn't and should be explicitly written in HTML (file, submit)? What is the principle of this separation?

+4  A: 

Good question.

I would think the input controls (e.g. input, select) are wrapped in Html helpers so they can maintain their own state via TempData without the user having to write a lot of code to achieve that. I would also think link and form controls are wrapped to give an easy and uniform way to specify the controller / action for those controls. Most other controls don't warrant either out-of-the-box state management or need controller / action urls built.

Of course there's nothing to stop you writing your own wrappers for whichever controls you like - e.g. here are a couple I use - here's one for an html label control:

public static string Label(this HtmlHelper helper, string fieldName, string labelText)
{
    var sb = new StringBuilder();
    sb.Append("<label for=\"");
    sb.Append(fieldName);
    sb.Append("\">");
    sb.Append(labelText);
    sb.Append("</label>");
    return sb.ToString();
}

And here's one that I use that wraps that label helper and a textbox to produce a uniform text input field complete with label:

public static string TextField(this HtmlHelper helper, string labelText, string fieldName, string value)
{
    return string.Concat(
     "<div>",
     helper.Label(fieldName, labelText),
     helper.TextBox(fieldName, value),
     "</div>");
}
Steve Willcock
+2  A: 

I have found Phil Haack's answer in thread "Html.SubmitButton() missing in Preview4?" concerning the problem:

Yeah, we are trying to keep the helpers somewhat minimalist. Not only that, we've received feedback from some people that many of our helpers are unnecessary. "I know HTML, why do I need a SubmitButton helper?".

We figured that since input buttons generally are not used to render user input, the helper method has marginal value. After all, with the VS HTML editor, you get intellisense when you type . It tells you which attributes are available. Our helper doesn't.

...

The thing we want to avoid is having a helper for every html element. That would make no sense: Html.Div.

We want to come up with a design rationale for helpers. Maybe we have one for all the common form elements, not just the ones that show user input. That's a possibility in which case we would include SubmitButton.

Right now, our rationale is any common form helper that renders user input, or any helper that renders routing info, has a helper...

Alexander Prokofyev