Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Is there a benefit to using the HtmlHelper in MVC?

Tags:

asp.net-mvc

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?

like image 476
Eric Schoonover Avatar asked Nov 08 '08 01:11

Eric Schoonover


4 Answers

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" />
like image 87
user17060 Avatar answered Oct 19 '22 23:10

user17060


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

like image 40
Timothy Khouri Avatar answered Oct 19 '22 22:10

Timothy Khouri


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!

like image 22
Codewerks Avatar answered Oct 19 '22 23:10

Codewerks


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.

like image 40
Glenn Avatar answered Oct 20 '22 00:10

Glenn