tags:

views:

428

answers:

6

Is there a specific reason why I should be using the Html.CheckBox, Html.TextBox, etc methods instead of just manually writing the HTML?

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

renders the following HTML

<input type="text" value="" name="uri" id="uri"/>

It guess it saves you a few key strokes but other than that. Is there a specific reason why I should go out of my way to use the HtmlHelpers whenever possible or is it just a preference thing?

+1  A: 

I haven't been doing MVC too long, but I've already written some extension methods to generate menu tabs based on Html.ActionLink. It allows me to be consistent with my usage and, if I decide to change how my CSS menus work, only modify a single method to output the new tab format.

The other use that I have made of them is in conditional output using ViewData to supply values to the controls.

tvanfosson
+1  A: 

One thing is for consistency...I for one always forget the name attribute. Plus, you can extend the functions for your own projects. They're not called helpers for nothing!

Codewerks
+1  A: 

The upside to using an abstraction layer is future proofing your code in a pluggable way. Maybe today, you create HTML 4 pages but tomorrow you want to create XHTML pages or XAML or XUL. That's a lot of changes if you just hard code the tags everywhere, especially if you've got hundreds of pages. If everything is calling this library, then all you've got to do is rewrite the library. The downside is that it is usually considered to be slightly less readable by humans. So, it most probably increases the cognitive demand on your maintenance programmers. These advantages and disadvantages really have nothing to do with MVC.

Glenn
+7  A: 

Another benefit is that if your ViewData contains a value matching the name of the field it will be populated.

e.g.

ViewData["FirstName"] = "Joe Bloggs"; 

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

will render

<input type="text" value="Joe Bloggs" id="FirstName" />
+2  A: 

It actually auto populates your textbox based upon first your ViewData.Model.uri and second by ViewData["uri"]. Doing it manually you'd need to do <input value="<%Html.Encode(ViewData.Model.Uri"%>" />

+5  A: 

There are huge benefits:

It has overloaded methods to pre-populate the values (formatted, and safe for HTML) just like the ViewState.

It allows built in support for the Validation features of MVC.

It allows you to override the rendering by providing your own DLL for changing the rendering (a sort of "Controller Adapter" type methodology).

It leads to the idea of building your own "controls" : http://www.singingeels.com/Articles/Building_Custom_ASPNET_MVC_Controls.aspx

Timothy Khouri
No, the ViewState is **not** there to preserve a textbox's value over the postback(s); that is the job of the IPostBackDataHandler (System.Web.UI namespace, System.Web assembly).
Andrei Rinea
Good correction of my terminology... +1 :)
Timothy Khouri