ListBox HTML Helper in ASP.NET MVC

Creating ListBox using ListBox HTML Helper in ASP.NET MVC

In this article, I am going to discuss how to create a ListBox using ListBox HTML Helper in the ASP.NET MVC application. Please read our previous article before proceeding to this article where we discussed how to create a checkbox using CheckBox HTML Helper in the MVC application.

What is a ListBox?

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.

Let us understand ListBox HTML Helper in MVC with an example.

To understand the ListBox HTML Helper in the ASP.NET MVC application, we are going to use the following City Table.

ListBox HTML Helper in MVC

We need to generate the following list box. Notice that for each city in the City table, there is an entry in the list box as shown in the below image.
ASP.NET MVC ListBox HTML Helper

Business Requirements:

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

For this demo, we are going to use the following “City” entity that we created using the ADO.NET entity framework in our previous article.

ListBox HTML Helper in ASP.NET MVC

Creating a View Model:

First, we need to create a View Model. In ASP.NET 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, and then add a new class file with the name CitiesViewModel. Once you create the CitiesViewModel then copy and paste the following code into it. This is the class that is going to be the Model for our view.

namespace HTML_HELPER.Models
{
    public class CitiesViewModel
    {
        public IEnumerable<string> SelectedCities { get; set; }
        public IEnumerable<SelectListItem> Cities { get; set; }
    }
}

Modify the Home Controller as shown below

namespace HTML_HELPER.Controllers
{
    public class HomeController : Controller
    {
        [HttpGet]
        public ActionResult Index()
        {
            CityDBContext dbContext = new CityDBContext();
            List<SelectListItem> citiesSelectListItems = new List<SelectListItem>();

            foreach (City city in dbContext.Cities.ToList())
            {
                SelectListItem selectList = new SelectListItem()
                {
                    Text = city.City_Name,
                    Value = city.City_ID.ToString(),
                    Selected = city.IsSelected
                };
                citiesSelectListItems.Add(selectList);
            }
            CitiesViewModel citiesViewModel = new CitiesViewModel()
            {
                Cities = citiesSelectListItems
            };
            return View(citiesViewModel);
        }

        [HttpPost]
        public string Index(IEnumerable<string> selectedCities)
        {
            if (selectedCities == null)
            {
                return "No cities selected";
            }
            else
            {
                StringBuilder sb = new StringBuilder();
                sb.Append("You selected - " + string.Join(",", selectedCities));
                return sb.ToString();
            }
        }
    }
}

Copy and paste the following code in the “Index.cshtml” view

@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 everything is working as expected.

In the next article, I am going to discuss Editor HTML Helper in ASP.NET MVC application. Here, in this article, I try to explain how to create ListBox using ListBox HTML Helper in ASP.NET MVC with an example. I hope this ListBox HTML Helper in MVCarticle will help you with your need.