ListBox HTML Helper in MVC

Creating ListBox using ListBox HTML Helper in MVC

In this article, I am going to discuss how to create ListBox using ListBox HTML Helper in MVC application. 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.

Please read our previous article before proceeding to this article where we discussed how to create a checkbox using CheckBox HTML Helper in MVC application. We are also going to work with the same example that we created in our previous article.

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

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

how to create ListBox using 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. 
ListBox using ListBox HTML Helper in MVC  

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 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 in it. This is the class which 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 “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 will discuss Editor HTML Helper in ASP.NET MVC application.

SUMMARY:

In this article, I try to explain how to create ListBox using ListBox HTML Helper in MVC step by step with a real-time example. I hope this ListBox HTML Helper in MVC article will help you with your need. I would like to have your feedback. Please post your feedback, question, or comments about this article.

Leave a Reply

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