HTML Helpers In ASP.NET MVC

I always knew that HTML Helpers are so much easy but most of the times, people confuse about these such as how to use them, what are they? When I did not have enough knowledge about ASP.NET MVC or any web-based framework, literally, I didn’t even care to learn the front-end.

I was just thinking that I’ll move with Microsoft Technologies in my career and always thought there might be some different approach for HTML instead of using plain HTML. Literally, I thought like that. Don’t laugh at me, I was just a very beginner with programming at that time. So, the answer to this question is, if you learn anything, it will never go in vain. What you’ve learned will work for you and will help you someday. So, always say yes to learn a new thing.

Most of the times, a new guy confuses regarding what approach he has to follow. My personal experience says you should know both the approaches because both are useful. In some scenarios, our plain HTML may not work as it should. At that moment, we can use HTML Helpers with fewer efforts and even don’t care about a lot of HTML attributes. HTML helpers make our work easy. With plain HTML, it takes a huge pile of efforts to bind our model properties with the form elements but with HTML helpers, we take advantage of strongly typed things. We see the IntelliSense in the View, which reduces a lot of our time and efforts.

Let me share the different HTML helpers with you.

HTML ControlHTML HelperStrongly Typed HTML Helpers
Anchor LinkHtml.ActionLink() 
CheckboxHtml.CheckBox()Html.CheckBoxFor()
Radio buttonHtml.RadioButton()Html.RadioButtonFor()
Multi Selected List BoxHtml.ListBox()Html.ListBoxFor()
TextboxHtml.TextBox()Html.TextBoxFor()
Hidden fieldHtml.Hidden()Html.HiddenFor()
Text areaHtml.TextArea()Html.TextAreaFor()
Dropdown, ComboboxHtml.DropDownList()Html.DropDownListFor()
LabelHtml.Label()Html.LabelFor()
PasswordHtml.Password()Html.PasswordFor()
Html TextHtml.Display()Html.DisplayFor()
It generates the html control based on the datatype of the model propertyHtml.Editor()Html.EditorFor()

These are different HTML Helpers which are used to generate HTML at the back-end. I would always prefer to use the HTML Helpers with “For” because it supports at compiling time, checking your properties. But if you’re using plain HTML helpers in which you pass the model property names in a string, then it will not support compile-time checking and if there is any problem in your HTML Helper properties, you’ll get runtime exceptions. So, always prefer to use the "For" extension HTML helpers e.g. CheckBoxFor, LabelFor, TextAreaFor.

Html.TextBox

Html.TextBox is loosely-typed because model property name is in the string. Here is the syntax for Html.TextBox().

MvcHtmlString Html.TextBox(string name, string value, object htmlAttributes)

And in a different scenario, we need to provide different parameters in HTML Helpers that’s why we should have the knowledge of HTML Helper overloads. Here is the MSDN link.

  1. @Html.TextBox("Name"nullnew { @class = "form-control" })   

It generates the HTML result as.

  1. <input class="form-control"   
  2.         id="Name"   
  3.         name="Name"   
  4.         type="text"   
  5.         value="" />  

This is how HTML Helper generates the HTML. Automatically, id and name attributes are set to the model property names. And you can see we have used @ razor syntax with the class because a class keyword is a reserved keyword in C#; that’s the way to set it for the HTML attribute. Then, we can again set it with Razor syntax.

Html.TextBoxFor

And if we discuss the Html.TextBoxFor, it is strongly-typed and very easy to use.

MvcHtmlString TextBoxFor(Expression<Func<TModel,TValue>> expression, object htmlAttributes)

  1. @Html.TextBoxFor(m => m.Name, new { @class = "form-control" })   

The HTML result is same as above of Html.TextBox. This technique gives you compile time exception handling. And the view will not run successfully on the server.

Html.TextArea()

Here is the TextArea HTML helper syntax.

MvcHtmlString Html.TextArea(string name, string value, object htmlAttributes)

Obviously, as I’ve already told you that there are many overloaded HTML helper functions, we can also set the number of rows and number of columns of any html.textarea.

  1. @Html.TextArea("Description"nullnew { @class = "form-control" })   

And here is the HTML result of this HTML helper.

  1. <textarea class="form-control"   
  2.             id="Description"   
  3.             name="Description"   
  4.             rows="2"  
  5.             cols="20">This is value</textarea>  

By default, the number of rows is 2 and number of columns is 20 for any text area.

Html.TextAreaFor()

This is the syntax for Html.TextAreaFor HTML helper.

MvcHtmlString TextAreaFor(<Expression<Func<TModel,TValue>> expression, object htmlAttributes)

So, this is the way we use TextAreaFor HTML helper.

  1. @Html.TextAreaFor(m => m.Description, new { @class = "form-control" })   

And the HTML generated through it looks like the following.

  1. <textarea class="form-control"   
  2.             cols="20"   
  3.             id="Description"   
  4.             name="Description"   
  5.             rows="2"></textarea>  

We already know that For extension methods support strongly typed functions; that’s why it supports compile time checking.

Html.Checkbox()

The most interesting HTML element is a checkbox. Here is the checkbox syntax -

MvcHtmlString CheckBox(string name, bool isChecked, Object htmlAttributes)

And you can see the individual HTML elements overloaded function on MSDN docs.

@Html.CheckBox("Married", true)

The HTML generated through this HTML helper is,

  1. <input checked="checked"   
  2.         id="Married"   
  3.         name=" Married"   
  4.         type="checkbox"   
  5.         value="true" />  

A true value is for checking the checkbox

Note
All the HTML helpers like DisplayFor, Display, DropDownList, DropDownListFor works the same as above HTML helpers are working. Now you have an idea how the HTML works render and how we use them. Now, I’ll just show you some important things in HTML Helpers.

Html.CheckBoxFor()

About a month ago, I was working on a project. And when I opened the browser with inspect element, I was really surprised to see what was happening under the hood. Literally, so much confused at that moment! Then I studied the things about Checkbox HTML Helper.

This is the Html.CheckBoxFor method signature

MvcHtmlString CheckBoxFor(<Expression<Func<TModel,TValue>> expression, object htmlAttributes)

And here is the code for html.checkboxfor

@Html.CheckBoxFor(m => m.Married)

This is how it renders into the HTML.

  1. <input data-val="true" data-val-required="The isNewlyEnrolled field is required."   
  2.         id="Married"   
  3.         name="Married"   
  4.         type="checkbox"   
  5.         value="true" />  
  6.   
  7. <input name="Married" type="hidden" value="false" /> 
Look here. It renders the additional hidden field with the same name and with value false. Now, the question is why it is rendering another extra HTML element with hidden type and with value false. Actually when you submit the form without checking the checkbox then it automatically picks up this hidden field with false checkbox value and then it submits the element to the form and if you check the checkbox then it submits the value with checked to the form.

@Html.Label()

This HTML helper is used to show the label of the form element in the view.

@Html.Label(“Name”)

And now it renders in the HTML as

<label for=”Name”></label>

@Html.LabelFor()

This HTML helper works the same and renders the same HTML in the browser.

@Html.LabelFor(“Name”) 

@Html.Editor

Most of the senior developers even don’t know how @Html.Editor works. It actually generates the HTML dependent upon the data type of the model properties at runtime. We don’t even think about the different HTML helpers. It automatically renders the textbox, text area, drop-down list dependent upon the datatype.  

Property DataTypeHtml Element
String<input type="text" >
Int<input type="number" >
decimal, float<input type="text" >
Boolean<input type="checkbox" >
Enum<input type="text" >
DateTime<input type="datetime" >

 Let’s see an example,

  1. @Html.Editor("Id")  // renders textbox numeric onlyName:  
  2. @Html.Editor("Name")              // renders textboxAge:   
  3. @Html.Editor("Age")                // renders textbox numeric onlyPassword:  
  4. @Html.Editor("Password")          // renders textbox alphanumericStatus:  
  5. @Html.Editor("Married")           Gender:  
  6. @Html.Editor("Gender")    // renders dropdown with male & femaleDoB:  
  7. @Html.Editor("DoB")                // renders textbox with datetime only And it works the same with Html.EditorFor   
@Html.ValidationMessage()

Yes if you’re using Html.ValidationMessage() HTML helper in your form and inspect the HTML, you’ll see some strange HTML. And even you don’t decide what is doing there under the hood. If you don’t know why we use Html.ValidationMessage() HTML helper then the answer to this question is if we want to show the validation messages in the form then we use ValidationMessage or ValidationSummary HTML helpers.

Now let’s suppose our HTML Helper is, 
  1. @Html.Editor("Name") <br />  
  2. @Html.ValidationMessage("Name"""new { @class = "text-danger" })  
Now it renders under the hood something like that,
  1. <input id="Name"   
  2.         name="Name"   
  3.         type="text"   
  4.         value="" />  
  5.   
  6.   
  7. <span class="field-validation-valid text-danger"   
  8.         data-valmsg-for="Name"   
  9.         data-valmsg-replace="true">  
  10. </span>  

Now, we want to show the custom error messages. So to show the custom error messages, we’ve 2 techniques.

  1.  Set the custom error message on a model property with data annotation attribute
    1. public class Student  
    2. {  
    3.     public int Id { get; set; }  
    4.     [Required(ErrorMessage="Please enter student name.")]  
    5.     public string Name { get; set; }  
    6.     public int Age { get; set; }  
    7. }  
  2. Set the custom error message Html.ValidationMessage html helper.
    1. @Html.TextBox("Name") <br />  
    2. @Html.ValidationMessageFor(m => m. Name, "Please enter person name."new { @class = "text-danger" })  

 This is how we use ValidationMessage html helper. 

Html.ValidationSummary()

It is used to show all the validation summary messages at a specific place where we use this HTML helper in the form. 

Just with placing this HTML helper, this is how it shows the error on the screen. 

@Html.ValidationSummary() 

What is ModelState.AddModelError()?

We can also add the model state error on a specific condition if all the values are right. Look how does it works,

  1. if (ModelState.IsValid)  
  2. {  
  3.     if (student.Name == "Usama")  
  4.     {  
  5.         ModelState.AddModelError("""This Name is already exists");  
  6.         return View(student);  
  7.     }  
  8.    
  9.     db.Students.Add(student);  
  10.     db.SaveChanges();  
  11.     return RedirectToAction("Index");  
  12. }  

 And if student.Name is “Usama” already exists in the table then it shows the error in ValidationSummary() html helper,


Look these are the records already in database, So the error is showing on the view like below, here we’re using this ValidationSummary statement in the view.
  1. @Html.ValidationSummary(true""new { @class = "text-danger" })  


This is how ValidationSummary validations are showing on the form. These are the validation summary messages at one place. 

Look here you can see the intelliSense and learn from it everything,


IntelliSense is telling the complete story, how it would behave in a differed scenarios. If you mark the excludePropertyErrors as true, then it will just show the model level errors and if it is ok, then it will show the error here which we’ve added in ModelStateDictionary with this command,
  1. ModelState.AddModelError("""This Name is already exists");  

 And if we mark it false, then it will show you the model level errors and the summary message errors as well as it is showing here.  


Conclusion

In this write-up, we learned from the IntelliSense, what different parameters are and in what place, you’ve to provide everything. We saw different HTML helpers and how they render under the hood. Sometimes, while using Checkbox HTML helper, it may not be working in different themes as we expect from it. That time, we have to manually remove or hide the false input type checkbox. We also saw how we can use the ValidationMessage and ValidationSummary and how we can add the ModelLevelError through actions in ModelStateDictionary. 
 
Just a word of advice - Always prefer to use the strongly-typed HTML helpers. I’ve not explained every HTML helper here because it is like spoon feeding, I’ve discussed the necessary things. Now, you can easily use them. 

Explore the different overloaded functions of HTML Helpers on your own. You can see each and every detail about these functions on MSDN.


Similar Articles