Microsoft developed ASP.NET MVC as a web application framework which implements the model–view–controller or more popularly known as MVC pattern. It happens to be open-source software, besides the ASP.NET Web Forms component.


In this blog, we shall discuss the process of implementing ListBox in MVC. Here, table “tblCity” is used for the demo.

For this demo, the “City” entity is used that is created using ADO.NET entity framework.

The first step is to generate a ViewModel class. In MVC, view models are used as techniques to transfer data between the view and the controller. Give a right click on the “Models” folder, and add a class file bearing name=CitiesViewModel.cs. Copy and paste the below mentioned code. This class will be the Model for the view.

public class CitiesViewModel


public IEnumerable<string> SelectedCities { get; set; }

public IEnumerable<SelectListItem> Cities { get; set; }


Next, right click on the folder called “Controllers” and then add a “HomeController”. Add the below two namespaces in the “HomeController”

Using MVCDemo.Models;

Using System.Text;

Copy and paste the following code.


public ActionResult Index()


SampleDBContext db = new SampleDBContext();

List<SelectListItem> listSelectListItems = new List<SelectListItem>();

for each (City city in db.Cities)


SelectListItem selectList = new SelectListItem()


Text = city.Name,

Value = city.ID.ToString(),

Selected = city.IsSelected




CitiesViewModel citiesViewModel = new CitiesViewModel()


Cities = listSelectListItems


return View(citiesViewModel);



public string Index(IEnumerable<string> selectedCities)


if (selectedCities == null)


return “No cities selected”;




StringBuilder sb = new StringBuilder();

sb.Append(“You selected – ” + string.Join(“,”, selectedCities));

return sb.ToString();



Next give a Right click on the method called “Index” action in “HomeController” and choose “Add View” from the context menu. Set

View Name = Index

View Engine = Razor

Then click “Add”.

Copy and paste the below mentioned code in “Index.cshtml”

@model MVCDemo.Models.CitiesViewModel


ViewBag.Title = “Index”;


<div style=”font-family:Arial”>


@using (Html.BeginForm())


@Html.ListBoxFor(m => m.SelectedCities, Model.Cities, new { size = 4 })

<br />

<input type=”submit” value=”Submit” />



To note that, if you want to select multiple items from the list box, you have to hold down the CTRL Key.

Keep coding!

If you want to enhance yourself in Dot Net Course and improve yourself through Dot NET training program; our institute, CRBtech Solutions would be of great help and support. We give a well-structured program for the best Dot Net Course. Among many reputed institutes of dot net training and placement in Pune, CRBtech has created a niche for itself.