Back to: ASP.NET Core Tutorials For Beginners and Professionals
ListBox HTML Helper in ASP.NET Core MVC
In this article, I am going to 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?
A ListBox in HTML is a user interface element that presents a list of options to the user, allowing them to select one or multiple items from the list. It’s often used in forms and user interfaces where users need to make selections from a predefined set of choices. A ListBox can display a scrollable list of items, making it suitable for presenting long lists of options.
A ListBox is a graphical control element that allows the user to select one or more items from the list box. The user clicks inside the box on an item to select it, sometimes in combination with the Shift or Ctrl, in order to make multiple selections. Clicking an item that has already been selected unselects it.
Key Characteristics of a ListBox:
- Selectable Items: A ListBox allows users to select one or more items from a list of options. The user can usually make selections by clicking on the items.
- 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).
- Scrollable: If the list of items is too long to fit within the available space, a ListBox typically includes a scroll bar to navigate through the list.
- 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.
- Multiple Selections: For multi-select ListBox, you can use the multiple attribute on the <select> element to allow users to select multiple items.
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.
ListBox HTML Helper in ASP.NET Core MVC:
In ASP.NET Core MVC, the ListBox HTML Helper is used to generate HTML markup for list box inputs within a view. A list box, also known as a dropdown list, presents a set of options to users, allowing them to select one or multiple items from the list. The ListBox HTML Helper simplifies the process of creating and binding list boxes to model properties.
ListBox 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 single-select list box. This method generates an HTML <select> element with <option> elements representing the available options. We need to generate the following list box.
We need 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, create a class file with the name 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, the 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, then add a new class file named CitiesViewModel. Once you create the CitiesViewModel, copy and paste the following code. This is the class that 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 Home Controller 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.
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, now run the application, and you should get the output as expected. The ListBox HTML Helper simplifies the process of creating and binding list boxes, making it easier to work with form inputs in your ASP.NET Core MVC application.
What are the Differences Between Html.ListBox and Html.ListBoxFor in ASP.NET Core MVC?
In ASP.NET Core MVC, both Html.ListBox and Html.ListBoxFor Methods are HTML Helper methods used to generate list box inputs in a view. However, they serve different purposes and are used in different contexts. Here’s a comparison of Html.ListBox and Html.ListBoxFor:
Html.ListBox:
This method is used when you want to manually generate a list box without being directly bound to a model. It allows you to define the list box’s name, options, selected values, and other attributes.
Syntax: @Html.ListBox(“name”, selectList, selectedValues, htmlAttributes)
- name: The name attribute of the list box.
- selectList: An instance of IEnumerable<SelectListItem> that defines the list of options.
- selectedValues: An array of values indicating which options should be pre-selected.
- htmlAttributes: An object that defines additional HTML attributes for the list box.
Example: @Html.ListBox(“selectedCities”, citiesViewModel.Cities, new { size = 7 })
Html.ListBoxFor:
This method is used when you want to generate a list box that is directly bound to a model property. It creates a list box with options based on the specified model property and its value. When the form is submitted, the selected value(s) are bound to the specified property.
Syntax: @Html.ListBoxFor(expression, selectList, htmlAttributes)
- expression: An expression that identifies the model property to which the list box is bound.
- selectList: An instance of IEnumerable<SelectListItem> that defines the list of options.
- htmlAttributes: An object that defines additional HTML attributes for the list box.
Example: @Html.ListBoxFor(m => m.SelectedCities, Model.Cities, new { size = 7 })
Usage:
- Html.ListBox: Used for manual generation of list boxes where you want control over the options and selected values.
- Html.ListBoxFor: Used when generating list boxes that are directly bound to a specific model property, ensuring proper model binding when the form is submitted.
The Html.ListBox is suitable for manually managing the list box’s options and selected values, while Html.ListBoxFor is used when you want to generate list boxes that are directly bound to a specific model property, ensuring proper model binding when the form is submitted.
In the next article, I am going to 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.