ListBox HTML HELPER

What is ListBox HTML Helper in ASP.NET MVC?

In ASP.NET MVC, the Html.ListBox() HTML helper is used to create a multi-select list box (<select multiple="multiple">). It allows users to select multiple options from a list.

Let’s add the ADO.NET data model to retrieve data from the database


Creating a View Model:

First, we need to create a View Model. In ASP.NET MVC, view models serve as a mechanism to transfer data between the controller and the view. To create a view model, right-click on the Models folder and add a new class file named CitiesViewModel. After creating the CitiesViewModel, copy and paste the following code into it. This class will act as the model for our view.


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

Update the Home Controller as demonstrated 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();
            }
        }
    }
}
                                        

Paste the following code into 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: To select multiple items from the list box, hold down the CTRL key. Execute the application and verify that everything functions correctly.