65.9K
CodeProject is changing. Read more.
Home

ASP.NET MVC – How to Create a ListBox?

starIconstarIconstarIconstarIcon
emptyStarIcon
starIcon

4.42/5 (10 votes)

May 12, 2014

CPOL

2 min read

viewsIcon

147089

How to create a ListBox in ASP.NET MVC

In the last blog post on ASP.NET MVC, we have discussed about implementing CheckBoxList. You can read that article here. In this article, we will go over implementing ListBoxes in ASP.NET MVC.

Let’s try to understand this with an example. We will be using tblCity table for this.

MVC1

The SQL scripts for creating tblCity table and inserting data into it are the following:

CREATE TABLE tblCity
(
ID INT IDENTITY PRIMARY KEY,
Name NVARCHAR(100) NOT NULL,
IsSelected BIT NOT NULL
)

Insert into tblCity values (‘London’, 0)
Insert into tblCity values (‘New York’, 1)
Insert into tblCity values (‘Sydney’, 1)
Insert into tblCity values (‘Mumbai’, 0)
Insert into tblCity values (‘Cambridge’, 0)

Our ultimate intention is to generate a screen like below:

MVCDemoRequirement

The requirements are as follows:

When a user selects one or more cities in the ListBox and clicks on Submit button, the CityIds of the selected cities should be displayed in a comma separated manner. When the user doesn’t select any of the cities and still clicks on Submit button, a message of No cities are selected should be appeared.

First of all, add an ADO.NET data model to retrieve data from the database. In this example, we will be using the tblCity entity which we have generated using ADO.NET Entity Framework in the previous article.

MVC7

Then create a ViewModel class. In ASP.NET MVC, ViewModel is a class that contains the fields which are represented in the strongly-typed view. It is used to pass data from a controller to a strongly-typed view.

Right click on the Models folder and add a class file with name CitiesViewModel.cs.

MVC1

Copy and paste following code to the CitiesViewModel class.

public class CitiesViewModel
{
    public IEnumerable<string> SelectedCities { get; set; }
    public IEnumerable<SelectListItem> Cities { get; set; }
}

MVC2

Then right click on the Controllers folder and add a HomeController. Include the following 2 namespaces in HomeController.

using MVCDemo.Models;
using System.Text;

Copy and paste the following code to the HomeController for displaying cities in ListBox.

[HttpGet]
public ActionResult Index()
{
    SampleDBContext db = new SampleDBContext();
    List<SelectListItem> listSelectListItems = new List<SelectListItem>();
            
    foreach (tblCity city in db.tblCities)
    {
        SelectListItem selectList = new SelectListItem()
        {
            Text = city.Name, 
            Value = city.ID.ToString(), 
            Selected = city.IsSelected
        };
        listSelectListItems.Add(selectList);
    }

    CitiesViewModel citiesViewModel = new CitiesViewModel()
    {
        Cities = listSelectListItems
    };

    return View(citiesViewModel);
}

MVC3

Then right click on the Index action method in HomeController and select Add View from the context menu.

MVC4

Set:

View Name = Index
View Engine = Razor

Model class = CitiesViewModel(MVCDemo.Models) and click Add.

MVC5

Copy and paste following code to the Index.cshtml.

@model MVCDemo.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 = 5 })
        <br />
        <input type=”submit” value=”Submit” />
}
</div>

MVC6

We have written the method for displaying cities by decorating it with [HttpGet] attribute in HomeController. But when a user clicks on the Submit button, the Postback has to be handled properly as well. Let’s add the method for this to HomeController by decorating it with [HttpPost] attribute.

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

MVC7

Now run the application and we will get a screen like below:

MVC8

When we select some cities, say London, Sydney and Cambridge and click on Submit button, a message like below will appear.

You selected – 1,3,5

Here 1,3 and 5 are the CityIds of London, Sydney and Cambridge respectively.

MVC9

Without selecting any cities and clicking on Submit button, a message like below will be appeared as expected.

No cities are selected

MVC10

MVC11

Reference