HTML Helpers in MVC: Part 2

This article shows how to render a radio button list control and a checkbox list control using HTML Helpers.

In the previous part of this series we saw how to render a text-box control and how to render a dropdownlist control. To learn more click here.

Example 1

To render a radio button using a HTML element we can use the form input element and pass the type attribute of the input element to the radio.



Run the application.



Let's see how to do the same thing using a HTML Helper.

To render a radio button using a HTML helper we can use a RadioButton or RadioButtonFor HTML Helper extension method.



First let's see how to render the radio button using the RadioButton extension method.


The first parameter expects a name for this radio button and the second parameter expects a value.

  1. @Html.RadioButton("MyCity","Delhi")  
Run the application.



The radio button is rendered using a HTML helper but doesn't have a text suffixed to the radio button. To suffix a text we can use another HTML helper called “DisplayName”.
  1. @Html.RadioButton("MyCity","Delhi") @Html.DisplayName("Delhi")  
Run the application.

Just like that we can render another radio button for Kolkata.



Run the application.



Example 2

Let's say for some reason whenever this page is requested by the users, we want Kolkata to be selected by default.

using a HTML element

To select Kolkata by default, we can use a checked attribute and pass checked as a value.
  1. <input type="radio" name="city" value="Kolkata" checked="checked" />Kolkata  
using a HTML Helper

We can use the second overloaded version of the RadioButton HTML helper where we can pass true.



Run the application.



There is another way to do the same thing using the RadioButton HTML Helper.

We can use the third overloaded version of this RadioButton that expects HtmlAttributes and in the previous article we learned how to initialize the values in this parameter.


  1. @Html.RadioButton("MyCity", "Kolkata", new { @checked = "checked" }) @Html.DisplayName("Kolkata")  
Run the application.



Example 3

In this example, we will see how to bind values to the RadioButton from a database table.

For the demo we will be using Entity Framework to retrieve the data from this table.



Step 1

The first step is to install the Entity Framework and for that go to Tools -> NuGet Package Manager -> Manage NuGet Packages for Solution.



Expand the Online packages then select nugget.org then select Entity Framework -> Click Install.



Click I accept.



Wait until it is installed.



Once the installation is complete, you will see the Green mark sign at the top-right corner of EntityFramework. Click Close.



Step 2

The next step is to add two class files to the Models folder.

Class file one

Provide this class file the name “City.cs” and add two auto-implemented properties.
  1. using System.Collections.Generic;  
  2. using System.ComponentModel.DataAnnotations.Schema;  
  3.   
  4. namespace HtmlHelpersTwo.Models
    {  
  5.    public class City
     {     
  6.    public int Id { getset; }  
  7.    public string CityName { getset; }  
  8.  }  
  9. }  
Since we are retrieving the records from an existing database table we need to map our class with the database table and for that we can use the table attribute present in System.ComponentModel.DataAnnotations.Schema namespace.
  1. using System.Collections.Generic;  
  2. using System.ComponentModel.DataAnnotations.Schema;  
  3.   
  4. namespace HtmlHelpersTwo.Models 
    {  
  5.    [Table("tblCity")]  
  6.    public class City 
       {  
  7.       public int Id { getset; }  
  8.    public string CityName { getset; }  
  9.    }  
  10. }  
Class file two

Provide this class file the name “CityDB.cs” and inherit this class from DbContext.
  1. using System.Data.Entity;  
  2. namespace HtmlHelpersTwo.Models
     {  
  3. public class CityDB : DbContext
        {  
  4.   
  5.    }  
  6. }  
NOTE

DbContext and DbSet is present in the System.Data.Entity namespace.

Now in this class add a property of type DbSet<City> as in the following:
  1. using System.Data.Entity;  
  2. namespace HtmlHelpersTwo.Models 
    {  
  3. public class CityDB : DbContext 
       {  
  4.    public DbSet<City> Cities { getset; }  
  5.    }  
  6. }  
To learn more about DbContext and DbSet click here.

Class file three

Add a class “CityList” and to this class and write the following:

  1. using System.Collections.Generic;  
  2. using System.Linq;  
  3.   
  4. namespace HtmlHelpersTwo.Models
     {  
  5.    public class CityList 
       {  
  6.       public string Selected { getset; }  
  7.       public List<City> Cities { get {  CityDB cityDB = new CityDB();  
  8.       return cityDB.Cities.ToList();  
  9.    }  
  10. }  
  11. }  
  12. }  
The Selected property will give us the selected value back and the Cities property will give us the Id and CityName from the Cities property.

After adding these class files build the solution.

Step 3

Add a connection string to the root web.config file with the same name as that of the CityDB class.
  1. <connectionStrings>  
  2. <add name="CityDB" connectionString="server=.;database=db_sample;user=sa;password=sql" providerName="System.Data.SqlClient"/>  
  3. </connectionStrings>  
Step 4

In the HomeController add another action method “IndexTwo”.
  1. public ActionResult IndexTwo()   
  2. {  
  3.   
  4.  return View();  
  5. }  
In this IndexTwo method, create an instance of the CityList class and pass it to the view.

NOTE

This CityList class is present in HtmlHelpersTwo.Models and HomeController is present in HtmlHelpersTwo.Controllers. So, before creating the instance of this class, we must import the namespace.
  1. public ActionResult IndexTwo()
     {  
  2.    CityList c = new CityList();  
  3.    return View(c);  
  4.  }  
Step 5

The next step is to add a strongly typed view.



Click Add.

Step 6

In the IndexTwo.cshtml, write the following.
  1. <body>  
  2. @using(Html.BeginForm()) {  
  3. foreach(var item in Model.Cities) {  
  4. @Html.RadioButtonFor(r => r.Selected, item.CityName)@item.CityName  
  5. }  
  6.   
  7. <br />  
  8. <input type="submit" name="name" value="Submit" />  
  9. }  
  10. </body>  
The Html.BeginForm() helper will create a form in which we are looping through the Model's Cities and here the model is CityList.

The first parameter is returning a radio button input element for each property. The expression will give us the selected item's value back.

In the second parameter we are passing CityName as a value.

@item.CityName will give us the name of the City.

Run the application.



Now whenever a user selects any of the radio buttons, we want the selected choice value to be displayed and since this Submit button will generate a post request we need to create an IndexTwo post method.
  1. [HttpPost]  
  2. public string IndexTwo(CityList cl) {  
  3. if(!string.IsNullOrEmpty(cl.Selected)) {  
  4. return "You selected " + cl.Selected;  
  5. }  
  6. else {  
  7. return "Select a choice";  
  8. }  
  9. }  
Above here we are checking whether or not the value for the Selected property is null. If the user selects a radio button and clicks submit then we are displaying the selected value.

Run the application.



Click Submit.



Render CheckBox List Control using Editor Templates

Example 1

To implement a checkbox list control using a HTML element, we can use the input element of type checkbox.



To implement a checkbox list using HTML Helpers, we use @Html.CheckBox.



The first overloaded version of the CheckBox extension method expects a parameter of string where we pass the name for the CheckBox control we create.
  1. @Html.CheckBox("HtmlHelper") @Html.DisplayName("Kolkata")  
Just as in the preceding, we can create another checkbox control for Delhi.
  1. @Html.CheckBox("HtmlHelper") @Html.DisplayName("Delhi")  
Run the application.



Example 2

Let's say for some reason we want Kolkata to be selected by default.

We can use the checked attribute of the input element.
  1. <input type="checkbox" name="myCity" value="Kolkata" checked="checked" /> Kolkata  
To do the same thing in HTML Helper, we can use the second overloaded version of the CheckBox method.



Pass a value of true and run the application.



Example 3

In this example we will see how to bind database records to a checkbox and we will also see how to create a strongly-typed checkbox list control using the Editor template.

Let's say our business requirement is such that, when a user selects any of the checkboxes and clicks the button, the selected checkbox value should be displayed.

For the demo we will be using Entity Framework to retrieve the data from this table.



Step 1

The first step is to install the Entity Framework and for that go to Tools -> NuGet Package Manager -> Manage NuGet Packages for Solution.



Expand the Online packages then select nugget.org then select Entity Framework then click Install.



Click I accept.



Wait until it is installed.



Once the installation is complete, you will see the Green mark sign at the top-right corner of EntityFramework. Click Close.



Step 2

The next step is to add two class files to the Models folder.

Class file one

Provide this class file the name “City.cs” and add two auto-implemented properties.
  1. using System;  
  2. namespace HtmlHelpersTwo.Models   
  3. {  
  4.    public class City
     {  
  5.    public int Id { get; set; }  
  6.    public string CityName { get; set; }  
  7.    public Nullable<bool> IsSelected { get; set; }  
  8.   }  
  9. }  
Since we are retrieving the records from an existing database table we need to map our class with the database table and for that we can use the table attribute present in the System.ComponentModel.DataAnnotations.Schema namespace.
  1. using System.ComponentModel.DataAnnotations.Schema;   
  2. using System;    
  3. namespace HtmlHelpersTwo.Models 
    {  
  4.    [Table("tblCity")]  
  5.    public class City {  
  6.    public int Id { get; set; }  
  7.    public string CityName { get; set; }  
  8.    public Nullable<bool> IsSelected { get; set; }  
  9. }  
  10. }  
Class file two

Provide this class file the name “CityDB.cs” and inherit this class from DbContext.
  1. using System.Data.Entity;  
  2. namespace HtmlHelpersTwo.Models 
    {  
  3.    public class CityDB : DbContext
     {  
      
  4.  }  
  5. }  
NOTE

DbContext and DbSet are present in the System.Data.Entity namespace.

Now in this class add a property of type DbSet<City> as in the following:
  1. using System.Data.Entity;  
  2. namespace HtmlHelpersTwo.Models
     {  
  3. public class CityDB : DbContext 
       {  
  4.    public DbSet<City> Cities { getset; }  
  5.    }  
  6. }  
To learn more about DbContext and DbSet click here.

After adding these class files build the solution.

Step 3

Add a connection string to the root web.config file with the same name as that of the CityDB class.
  1. <connectionStrings>  
  2. <add name="CityDB" connectionString="server=.;database=db_sample;user=sa;password=sql" providerName="System.Data.SqlClient"/>  
  3. </connectionStrings>  
Step 4

In the HomeController create another action method “IndexTwo”.
  1. public ActionResult IndexTwo()  
  2.  {  
  3. return View();  
  4. }  
In this action method, create an instance of the CityDB class and pass the Cities property to the view.
  1. public ActionResult IndexTwo()   
  2. {  
  3. CityDB cityDB = new CityDB();  
  4. return View(cityDB.Cities);  
  5. }  
Step 5

Expand the Home folder in the Solution Explorer and add another folder “Editor Templates”.



In this Editor Templates folder, add a view.



NOTE

The name of the view must match with the name of the Model, in other words City.



This City class contains all the properties. Now whether a checkbox is selected or not which property will determine that, the IsSelected property and the name will be determined by the CityName property.

@model CheckBoxHTMLHelper.Models.City
  1. @Html.CheckBoxFor(c => c.IsSelected)  
  2. @Html.DisplayNameFor(n => n.CityName)  
But when we post this Editor template back to the server, we want the Id and CityName to retain its values and for that we can use the hidden field or else this value will be null.

@model CheckBoxHTMLHelper.Models.City
  1. @Html.HiddenFor(h => h.Id)  
  2. @Html.HiddenFor(name => name.CityName)  
  3. @Html.CheckBoxFor(c => c.IsSelected)  
  4. @Html.DisplayNameFor(n => n.CityName)  
Step 6

The next step is to add an IndexTwo view.

Click Add.

On the view we want a list of Cities. So, the model must be IEnumerable of City.



To call the EditorTemplate in this IndexTwo view, we can use the EditorForModel HTML Helper.

@model IEnumerable<CheckBoxHTMLHelper.Models.City>
  1. @using(Html.BeginForm())  
  2.  {  
  3.   
  4. @Html.EditorForModel()  
  5.   
  6. }  
What this EditorForModel will do is, it will look for an editor template with the same name as the type, which is City.

When the user selects any of the checkboxes and clicks the button, we want to display the selected value. For that first we need to add a submit button.

@model IEnumerable<CheckBoxHTMLHelper.Models.City>
  1. @using(Html.BeginForm())  
  2.  {  
  3. @Html.EditorForModel()  
  4. <br />  
  5. <br />  
  6. <input type="submit" name="submit" value="Submit" />  
  7. }  
Run the application.


The next step is to create an HttpPost IndexTwo action method.
  1. [HttpPost]  
  2. public string IndexTwo(List<City> city) {  
  3. if(city.Count(x => x.IsSelected) == 0) {  
  4. return " Select a Choice";  
  5. }  
  6. else {  
  7. System.Text.StringBuilder sb = new System.Text.StringBuilder();  
  8. sb.Append("You Selected - ");  
  9. foreach(City item in city) {  
  10. if(item.IsSelected) {  
  11. sb.Append(item.CityName + ", ");  
  12. }  
  13. }  
  14. sb.Remove(sb.ToString().LastIndexOf(","), 1);  
  15. return sb.ToString();  
  16. }  
  17. }  
Procedure: 
  • In the the preceding HttpPost method, we passed a List of Cities as a parameter.
  • There is an extension method in the System.Linq namespace “Count” that will provide us the number of selected items. if(city.Count(x => x.IsSelected) == 0). If the selected property value is zero then that means no item is selected and we are returning return "Select a Choice";
  • If a user selects any of the items then if the block condition will be false and it will come to the else block in which we created a new object of the StringBuilder class. Inside the foreach loop, we appended the CityName of the selected checkbox.

Run the application.


Click Submit.

 
I hope you like it. Thank you.