Form Tag Helper And Other Common Tag Helpers In ASP.NET Core MVC

Introduction

In my previous article, I have explained about the tag helper. This article explains about working with forms and other HTML elements that are used with the form using tag helper. The HTML form provides a way to post the data back to the server.

Form Tag Helper

Form Tag Helper generates the HTML form elements with action attribute value for MVC Controller action (named route). It is an alternative to HTML helpers Html.BeginForm and Html.BeginRouteForm. It generates hidden "Request Verification Token" to prevent the cross-site request forgery if the post method is decorated with ValidateAntiForgeryToken attribute. We can also supply route value parameter of post method using "asp-route-<parameter name>" attribute. Here, <pameter name> is added to the route value. This is same as routeValues parameter passed to Html.BeginForm and Html.BeginRouteForm.

Example
  1. <form asp-controller="Home" asp-action="Save" method="post">  
  2.    <!-- Input and Submit elements -->  
  3. </form>  
Generated HTML

 
The action attribute value is generated from the FORM tag helper attributes: asp-controller and asp-action. The Form Tag Helper also generates "Request Verification Token" (in the hidden field) to prevent cross-site request forgery.
Input Tag Helper

It binds an HTML input element to the Model expression in Razor View. It can generate the id and name attribute based on the expression specified in the asp-for attribute. It is capable to set HTML type attribute value based on the Model type and data annotation applied to the Model property. It never overwrites the type of an attribute if we have specified. It generates HTML5 base validation attributes from the data annotation applied to the model property. It provides strong typing with model. If we change the Model property name and do not change the tag helper, it throws an error.
 
 .net Type Input Type
 string text
bool checkbox
datetime datetime
byteNumber
intNumber
doubleNumber
singleNumber
 
It also considers the data annotation attributes of Model property to generate the type of input. The following table contains some examples of data annotation and type.
 
 Data Annotation attribute Input type
DataType(DataType.Password) 
 password
 EmailAddress email
 Uri uri
 HiddenInput hidden
 Phone tel
 [DataType(DataType.Date)] date
 [DataType(DataType.Time)] time
 
Example - Model Class
  1. using System.ComponentModel.DataAnnotations;  
  2.   
  3. namespace FormTagHelper.Models  
  4. {  
  5.     public class UserViewModel  
  6.     {  
  7.         public int UserId { getset; }  
  8.         public string UserName { getset; }  
  9.         [EmailAddress]  
  10.         public string EmailAdress { getset; }  
  11.     }  
  12. }   
HTML in cshtml(\Views\Home\index.cshtml)
  1. <div class="row">  
  2.   
  3.     <form asp-controller="Home" asp-action="Save" method="post">  
  4.         <!-- Input and Submit elements -->  
  5.         UserId : <input asp-for="UserId" /><br />  
  6.         User Name:<input asp-for="UserName" /><br />  
  7.         Email Address: <input asp-for="EmailAdress" />  
  8.     </form>  
  9. </div>   
Generated HTML

 
In the preceding example, the data annotation applied to the email property generated the metadata on the Model and the input tag helper uses this metadata to generate HTML5 attribute.
 
The "asp-for" attribute is a ModelExpression and assignment (right-hand side) is lambda expression. It means, asp-for = "propertyName" is equvalent to o=>o.propertyName in the generated code that does not require prefix model. We can also use @ character to start an inline expression used with the tag helper.
  1. @{  
  2.     var myNumber = 5;  
  3. }  
  4. <input asp-for="@myNumber" />  
Generated HTML

 
 
Textarea Tag Helper

It is very similar to Input Tag Helper. It generates the name and id attribute based on the Model and data annotation attributes from the Model. It provides strong typing with Models. It is an alternative to Html.TextAreaFor.
 
Example
  1. Address : <textarea asp-for="Address"></textarea>  
Generated HTML

 
 
Label Tag Helper
 
It generates the label caption for expression supplied with asp-for attribute. It is an alternative to Html.LabelFor. It will get the description of the lable value from "Display" attribute automatically. It generates less markup than the HTML label element. It is strongly typed with model property.
 
Example:
  1. <label asp-for="PhoneNumber"></label>  
  2. <input asp-for="PhoneNumber" /> <br />  
Generated HTML

 
 
It generates consistent id and for attribute, so that they can be correctly associated. The caption of the label comes from "Display" attribute on the Model property. If the Model property does not contain the "Display" attribute, it will generate the caption same as property name.
 
Select Tag Helper
 
It generates select and associate option elements for our model property. It is an alternative to Html.DropDownListFor and Html.ListBoxFor. It supports binding to the Model property using asp-for attribute and asp-items attribute used for specifying the options.
 
Example - Model
  1. public class FruitViewModel  
  2. {  
  3.     public string Fruit { getset; }  
  4.     public List<SelectListItem> Fruits { getset; }  
  5. }  
Controller Action method (HomeController)
  1. public IActionResult SelectExample()  
  2. {  
  3.     FruitViewModel fruit = new FruitViewModel();  
  4.     fruit.Fruits = new List<SelectListItem>  
  5.     {  
  6.         new SelectListItem { Value = "1", Text = "Apple" },  
  7.         new SelectListItem { Value = "2", Text = "Banana" },  
  8.         new SelectListItem { Value = "3", Text = "Mango"  },  
  9.         new SelectListItem { Value = "4", Text = "Orange"  },  
  10.     };  
  11.     fruit.Fruit = "2";  
  12.     return View(fruit);  
  13. }  
View (\Views\Home\SelectExample.cshtml)
  1. @model FormTagHelper.Models.FruitViewModel  
  2.   
  3. <select asp-for="Fruit" asp-items="Model.Fruits"></select>  
Generated HTML

 
In the preceding example, the “Fruit” model property has value “2” hence selected attribute has generated HTML.

A View Model is more robust to provide MVC metadata and generally less problematic than the ViewBag and ViewData. The Select Tag Helper can also be used with enum property and generate the SelectListItem element from the enum values.
 
Example

Model
  1. public class CityEnumViewModel  
  2. {  
  3.     public CityEnum EnumCity { getset; }  
  4. }  
  5.   
  6. public enum CityEnum  
  7. {  
  8.     [Display(Name = "Amdavad")]  
  9.     Ahmedabad,  
  10.     [Display(Name = "Vadodara")]  
  11.     Baroda,  
  12.     Gandhinagar,  
  13.     Bhavnagar,  
  14.     Surat,  
  15.     Bharuch,  
  16.     Rajkot  
  17. }  
View (Views\Home\SelectWithEnum.cshtml)
  1. @model FormTagHelper.Models.CityEnumViewModel  
  2.   
  3. <select asp-for="EnumCity" asp-items="Html.GetEnumSelectList<CityEnum>()"></select>  
Generated HTML

 
 
Option Group
 
The Option Group (optgroup) element is generated View Model that contains one or more SelectListGroup objects. In the following example, CityViewModelGroup groups the SelectListItem element into the "Gujarat" and "Maharashtra".
 
Model
  1. public class CityViewModel  
  2. {  
  3.     public string City { getset; }  
  4.     public List<SelectListItem> CityList { getset; }  
  5. }  
Controller
  1. public IActionResult SelectOptionGroup()  
  2. {  
  3.     var gujaratGroup = new SelectListGroup { Name = "Gujarat" };  
  4.     var maharastraGroup = new SelectListGroup { Name = "Maharastra" };  
  5.   
  6.     CityViewModel city = new CityViewModel();  
  7.     city.CityList = new List<SelectListItem>  
  8.     {  
  9.         new SelectListItem  
  10.         {  
  11.             Value = "1",  
  12.             Text = "Ahmedabad",  
  13.             Group = gujaratGroup  
  14.         },  
  15.         new SelectListItem  
  16.         {  
  17.             Value = "2",  
  18.             Text = "Gandhinagar",  
  19.             Group = gujaratGroup  
  20.         },  
  21.         new SelectListItem  
  22.         {  
  23.             Value = "3",  
  24.             Text = "Bhavangar",  
  25.             Group = gujaratGroup  
  26.         },  
  27.         new SelectListItem  
  28.         {  
  29.             Value = "4",  
  30.             Text = "Mumbai",  
  31.             Group = maharastraGroup  
  32.         },  
  33.         new SelectListItem  
  34.         {  
  35.             Value = "5",  
  36.             Text = "Pune",  
  37.             Group = maharastraGroup  
  38.         },  
  39.         new SelectListItem  
  40.         {  
  41.             Value = "6",  
  42.             Text = "Nasik",  
  43.             Group = maharastraGroup  
  44.         }  
  45.     };  
  46.     return View(city);  
  47. }  
View (Views\Home\SelectOptionGroup.cshtml)
  1. @model FormTagHelper.Models.CityViewModel  
  2.   
  3. <select asp-for="City" asp-items="Model.CityList"></select>  
Output

 

Generated HTML

 
Summary
 
In this article, I have explained about form tag helper and other common tag helpers, such as input, textarea, drop-down, and label. Also, we saw the equivalent HTML helpers

Up Next
    Ebook Download
    View all
    Learn
    View all