Click here to Skip to main content
15,885,985 members
Articles / Web Development / ASP.NET

ASP.NET MVC – How to Create a ListBox?

Rate me:
Please Sign up or sign in to vote.
4.42/5 (11 votes)
11 May 2014CPOL2 min read 145.6K   10   4
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:

SQL
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.

C#
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.

C#
using MVCDemo.Models;
using System.Text;

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

C#
[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:

C#
View Name = Index
View Engine = Razor

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

MVC5

Copy and paste following code to the Index.cshtml.

C#
@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.

C#
[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

Image 15 Image 16

License

This article, along with any associated source code and files, is licensed under The Code Project Open License (CPOL)


Written By
Software Developer
India India
Arun Ramachandran is a Software Engineer having hands on experience in different Microsoft Technologies who is presently working in Experion Technologies, India. He has written over 95 articles on the subject on his blog at http://BestTEchnologyBlog.com. Along with 3 years of hands on experience he holds a Master of Computer Applications degree from Cochin University of Science & Technology (CUSAT).

Comments and Discussions

 
GeneralThank You Pin
Priyanka Kale27-Feb-18 21:25
Priyanka Kale27-Feb-18 21:25 
Very helpful and Great information,
I appreciate advise especially coming from a professional.
Thanks again and keep up the great work!
GeneralNice Article. Pin
Pooja Dalvi18-Dec-17 21:42
Pooja Dalvi18-Dec-17 21:42 
QuestionCan we fill the items of ListBox by setting an ID for this control. Pin
Sudarshan Kumar Singh7-Oct-17 2:49
Sudarshan Kumar Singh7-Oct-17 2:49 
QuestionHow would you post back the viewmodel? Pin
Member 1159774110-Apr-15 11:39
Member 1159774110-Apr-15 11:39 

General General    News News    Suggestion Suggestion    Question Question    Bug Bug    Answer Answer    Joke Joke    Praise Praise    Rant Rant    Admin Admin   

Use Ctrl+Left/Right to switch messages, Ctrl+Up/Down to switch threads, Ctrl+Shift+Left/Right to switch pages.