ListBox HTML Helper in ASP.NET Core MVC

ListBox HTML Helper in ASP.NET Core MVC

In this article, I will discuss How to Generate a ListBox using ListBox HTML Helper in ASP.NET Core MVC Application with Examples. Please read our previous article, where we discussed How to Generate Check Boxes using CheckBox HTML Helper in ASP.NET Core MVC.

What is a ListBox in Web Application?

A ListBox in web applications is one of the input elements that allows users to select one or more items from a list displayed within a box. Users interact with a ListBox by clicking on the items it contains, which can be plain text items or more complex elements depending on the application’s requirements.

Key Characteristics of a ListBox:
  • Multiple Selections: A ListBox can be configured to allow users to select multiple items. This is typically achieved by holding down the Ctrl (or Command on macOS) key while clicking to select or deselect individual items or using the Shift key to select a range of contiguous items.
  • Scrollable: If the number of items exceeds the space available to display them, the ListBox can become scrollable, allowing users to navigate through the list without changing its overall size or the layout of the page.
  • Single-Select and Multi-Select Modes: A ListBox can operate in single-select mode, where users can select only one item at a time, or multi-select mode, where users can select multiple items simultaneously (usually by holding down the Ctrl key or Shift key).
  • HTML Structure: In HTML, a ListBox is created using the <select> element. Inside the <select> element, you can include one or more <option> elements, each representing an item in the list.
  • Labeling and Values: Each <option> element can have both display text and a corresponding value associated with it. The value is what gets sent to the server when the form is submitted.
Example of a Single Select ListBox in HTML:
<label for="fruits">Select a fruit:</label>
<select id="fruits" name="selectedFruit">
    <option value="apple">Apple</option>
    <option value="banana">Banana</option>
    <option value="orange">Orange</option>
    <option value="grape">Grape</option>
</select>
Example of a Multi-Select ListBox in HTML:
<label for="colors">Select your favorite colors:</label>
<select id="colors" name="selectedColors" multiple>
    <option value="red">Red</option>
    <option value="blue">Blue</option>
    <option value="green">Green</option>
    <option value="yellow">Yellow</option>
</select>

In the Multi Select ListBox example, the multiple attribute on the <select> element enables users to select multiple colors at once. ListBoxes are valuable for gathering user choices, allowing users to select preferences, and making multiple selections from a list of options.

How Do We Create a ListBox Using HTML Helper in ASP.NET Core MVC?

To create a ListBox using HTML Helpers in ASP.NET Core MVC, we need to use Html.ListBox or Html.ListBoxFor methods within our Razor views. The Html.ListBox method is used when you want to specify the name of the form field manually, while Html.ListBoxFor is used with model properties, providing a strongly typed approach. That means the ListBox() HTML Helper method is loosely typed, whereas the ListBoxFor() HTML Helper method is strongly typed.

What is ListBoxFor HTML Helper in ASP.NET Core MVC?

The ListBoxFor HTML helper in ASP.NET Core MVC is a server-side helper used to generate a <select> HTML element with the “multiple” attribute, allowing users to select multiple options from a list. The ListBoxFor helper is specifically designed to work with model properties. It is strongly typed, meaning it binds directly to model properties in your MVC application, ensuring compile-time checking of the property names you are binding to, which reduces the risk of errors.

Syntax: @Html.ListBoxFor(model => model.SelectedIds, new SelectList(Model.AvailableOptions, “Value”, “Text”))
Here,

  • model => model.SelectedIds indicates the model property to which the ListBoxFor will bind. This property should be a collection that will hold the values of the selected options.
  • new SelectList(Model.AvailableOptions, “Value”, “Text”) is used to generate the list items for the <select> element. Model.AvailableOptions is a collection within your model that holds the options to be displayed. “Value” and “Text” specify the property names in AvailableOptions that will be used for the option values and display texts, respectively.
List Box Example using ListBoxFor HTML Helper in ASP.NET Core MVC:

You can use the ListBoxFor HTML Helper Method in the ASP.NET Core MVC Application to generate a list box. This method generates an HTML <select> element with <option> elements representing the available options. We need to generate the following list box.

ListBox Example using ListBoxFor HTML Helper in ASP.NET Core MVC

We want to allow the user to select one or more cities from the ListBox. Once the user selects the cities and clicks on the Submit button, we need to display the names of the selected cities separated by a comma. If the user doesn’t select any city and clicks on the Submit button, then the No Cities are Selected message should be displayed.

Creating Models:

First, you need a model that contains a list of items to populate the ListBox and possibly a property to hold the selected item(s). First, create a class file named City.cs and copy and paste the following code into it.

namespace HTML_HELPER.Models
{
    public class City
    {
        public int CityId { get; set; }
        public string? CityName { get; set; }
        public bool IsSelected { get; set; }
    }
}

Next, we need to create a View Model. In ASP.NET Core MVC, view models are nothing but a mechanism to shuttle data between the controller and the view. To create the View Model, right-click on the Models folder and add a new class file named CitiesViewModel. Once you create the CitiesViewModel, copy and paste the following code. This class is going to be the model for our view.

using Microsoft.AspNetCore.Mvc.Rendering;
namespace HTML_HELPER.Models
{
    public class CitiesViewModel
    {
        public IEnumerable<int>? SelectedCities { get; set; }
        public IEnumerable<SelectListItem>? Cities { get; set; }
    }
}

Next, we need to modify the HomeController as follows:

using HTML_HELPER.Models;
using Microsoft.AspNetCore.Mvc;
using Microsoft.AspNetCore.Mvc.Rendering;
using System.Text;

namespace HTML_HELPER.Controllers
{
    public class HomeController : Controller
    {
        private List<City> CityList;
        public HomeController() 
        {
            CityList = new List<City>()
            {
                new City(){ CityId = 1, CityName = "London", IsSelected = false },
                new City(){ CityId = 2, CityName = "New York", IsSelected = false },
                new City(){ CityId = 3, CityName = "Sydney", IsSelected = false },
                new City(){ CityId = 4, CityName = "Mumbai", IsSelected = false },
                new City(){ CityId = 5, CityName = "Cambridge", IsSelected = false },
                new City(){ CityId = 6, CityName = "Delhi", IsSelected = false },
                new City(){ CityId = 7, CityName = "Hyderabad", IsSelected = false }
            };
        }

        [HttpGet]
        public ActionResult Index()
        {
            List<SelectListItem> citiesSelectListItems = new List<SelectListItem>();

            foreach (City city in CityList)
            {
                SelectListItem selectList = new SelectListItem()
                {
                    Text = city.CityName,
                    Value = city.CityId.ToString(),
                    Selected = city.IsSelected
                };
                citiesSelectListItems.Add(selectList);
            }
            CitiesViewModel citiesViewModel = new CitiesViewModel()
            {
                Cities = citiesSelectListItems
            };
            return View(citiesViewModel);
        }

        [HttpPost]
        public string Index(IEnumerable<int> selectedCities)
        {
            if (selectedCities == null)
            {
                return "No Cities Selected";
            }
            else
            {
                //First Fetch the Names of the Cities Selected
                var CityNames = CityList
                               .Where(t => selectedCities.Contains(t.CityId))
                               .Select(item => item.CityName).ToList();

                StringBuilder sb = new StringBuilder();
                sb.Append("Your Selected City Names - " + string.Join(",", CityNames));
                return sb.ToString();
            }
        }
    }
}

Next, modify the Index.cshtml view file as follows.

@model HTML_HELPER.Models.CitiesViewModel
@{
    ViewBag.Title = "Index";
}
<div style="font-family:Arial">
    <h2>Index</h2>
    @using (Html.BeginForm())
    {
        @Html.ListBoxFor(m => m.SelectedCities, Model.Cities, new { size = 7 })
        <br />
        <input type="submit" value="Submit" />
    }
</div>

Note: In order to select multiple items from the list box, you need to hold down the CTRL Key. Run the application and see if everything is working as expected.

What is ListBox HTML Helper in ASP.NET Core MVC?

The ListBox HTML Helper in ASP.NET Core MVC is a server-side helper used to generate a list box (a <select> element with the “multiple” attribute) on a web page. To use the ListBox HTML Helper, you generally need to specify the name of the form field and a selection list (usually provided as SelectList or IEnumerable<SelectListItem>). Optionally, you can also include HTML attributes to customize the appearance or behavior of the list box.

Syntax: @Html.ListBox(“MyListBox”, Model.MySelectListItems, new { @class = “my-custom-class” })
Here:

  • “MyListBox” is the name of the form field.
  • Model.MySelectListItems is the collection that populates the list box, where MySelectListItems is typically a property of the model passed to the view containing a collection of SelectListItem objects.
  • new { @class = “my-custom-class” } represents HTML attributes to add to the generated <select> element, such as a CSS class.
ListBox Example using ListBox HTML Helper in ASP.NET Core MVC:

Let us understand How we can use the ListBox HTML Helper in ASP.NET Core MVC Application, which is not a strongly typed HTML helper. We are going to do the same example using ListBox HTML Helper. So, modify the Home Controller class as follows.

using HTML_HELPER.Models;
using Microsoft.AspNetCore.Mvc;
using Microsoft.AspNetCore.Mvc.Rendering;
using System.Text;

namespace HTML_HELPER.Controllers
{
    public class HomeController : Controller
    {
        private List<City> CityList;
        public HomeController() 
        {
            CityList = new List<City>()
            {
                new City(){ CityId = 1, CityName = "London", IsSelected = false },
                new City(){ CityId = 2, CityName = "New York", IsSelected = false },
                new City(){ CityId = 3, CityName = "Sydney", IsSelected = false },
                new City(){ CityId = 4, CityName = "Mumbai", IsSelected = false },
                new City(){ CityId = 5, CityName = "Cambridge", IsSelected = false },
                new City(){ CityId = 6, CityName = "Delhi", IsSelected = false },
                new City(){ CityId = 7, CityName = "Hyderabad", IsSelected = false }
            };
        }

        [HttpGet]
        public ActionResult Index()
        {
            List<SelectListItem> citiesSelectListItems = new List<SelectListItem>();

            foreach (City city in CityList)
            {
                SelectListItem selectList = new SelectListItem()
                {
                    Text = city.CityName,
                    Value = city.CityId.ToString(),
                    Selected = city.IsSelected
                };
                citiesSelectListItems.Add(selectList);
            }
            CitiesViewModel citiesViewModel = new CitiesViewModel()
            {
                Cities = citiesSelectListItems
            };

            ViewBag.CitiesViewModel = citiesViewModel;

            return View();
        }

        [HttpPost]
        public string Index(IEnumerable<int> selectedCities)
        {
            if (selectedCities == null)
            {
                return "No Cities Selected";
            }
            else
            {
                //First Fetch the Names of the Cities Selected
                var CityNames = CityList
                               .Where(t => selectedCities.Contains(t.CityId))
                               .Select(item => item.CityName).ToList();

                StringBuilder sb = new StringBuilder();
                sb.Append("Your Selected City Names - " + string.Join(",", CityNames));
                return sb.ToString();
            }
        }
    }
}

Next, modify the Index.cshtml file as follows:

@{
    ViewBag.Title = "Index";
    CitiesViewModel citiesViewModel = ViewBag.CitiesViewModel;
}
<div style="font-family:Arial">
    <h2>Index</h2>
    @using (Html.BeginForm())
    {
        @*@Html.ListBox("selectedCities", citiesViewModel.Cities, citiesViewModel.SelectedCities)*@
        @Html.ListBox("selectedCities", citiesViewModel.Cities, new { size = 7 })
        <br />
        <input type="submit" value="Submit" />
    }
</div>

With the above changes in place, run the application, and you should get the expected output. 

What are the Differences Between ListBox and ListBoxFor in ASP.NET Core MVC?

In ASP.NET Core MVC, ListBox and ListBoxFor are HTML helper methods used to create a list box (a select element) that allows users to select one or more items. While both serve similar purposes, they differ primarily in their usage syntax and how they bind to model properties. Here’s a breakdown of the differences:

ListBox:
  • Usage: It creates a list box without strongly typed model binding. The name parameter corresponds to the name of the form field, and it collects the selected value(s) upon form submission.
  • Flexibility: Since it is not strongly tied to a model property, ListBox offers more flexibility in scenarios where you don’t have a direct model property to bind or when working with dynamic views.
  • Binding: The binding is manual. You must ensure that the selected values match those in your model or data source, especially in postback scenarios.
ListBoxFor:
  • Usage: It is used for strongly typed model binding. The expression parameter is a lambda expression that identifies the model property to which to bind. This approach integrates tightly with the model validation and binding features of ASP.NET Core MVC.
  • Strong Typing: ListBoxFor ensures compile-time checking of the expression passed to it, reducing the risk of errors due to mistyped property names.
  • Model Binding: It automatically binds the selected value(s) to the specified model property. This is particularly useful for scenarios involving form submissions and model validation, as it simplifies the process of capturing and validating user input.
Choosing Between ListBox and ListBoxFor:

The choice between ListBox and ListBoxFor depends on the specific requirements of your application:

  • Use ListBox when you need a dropdown list that is not directly tied to a model property or when working in a dynamically generated UI where model properties might not be known at compile time.
  • Use ListBoxFor when working with a strongly typed model where you want to take advantage of MVC’s model binding and validation features. It’s particularly useful in forms where capturing user input directly into a model is desired.

In the next article, I will discuss Editor HTML Helper in ASP.NET Core MVC Application. In this article, I explain How to Create ListBox using ListBox HTML Helper in ASP.NET Core MVC Application with Examples. I hope you enjoy this ListBox HTML Helper in ASP.NET Core MVC article.

Leave a Reply

Your email address will not be published. Required fields are marked *