Click here to Skip to main content
65,938 articles
CodeProject is changing. Read more.
Articles
(untagged)

ASP.NET MVC – How to Create a ListBox?

0.00/5 (No votes)
11 May 2014 2  
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.

<img alt="MVC1" class="alignnone wp-image-2252" src="771999/mvc1.png" style="width: 300px; height: 152px;" />

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 (&lsquo;London&rsquo;, 0)
Insert into tblCity values (&lsquo;New York&rsquo;, 1)
Insert into tblCity values (&lsquo;Sydney&rsquo;, 1)
Insert into tblCity values (&lsquo;Mumbai&rsquo;, 0)
Insert into tblCity values (&lsquo;Cambridge&rsquo;, 0)

Our ultimate intention is to generate a screen like below:

<img alt="MVCDemoRequirement" class="alignnone wp-image-2289" height="201" src="771999/mvcdemorequirement1.png" width="200" />

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.

<img alt="MVC7" class="alignnone wp-image-2292" height="414" src="771999/mvc71.png" width="600" />

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.

<img alt="MVC1" class="alignnone wp-image-2316" height="379" src="771999/mvc18.png" width="600" />

Copy and paste following code to the CitiesViewModel class.

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

<img alt="MVC2" class="alignnone wp-image-2301" height="262" src="771999/mvc21.png" width="600" />

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);
}

<img alt="MVC3" class="alignnone wp-image-2302" height="496" src="771999/mvc31.png" width="600" />

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

<img alt="MVC4" class="alignnone wp-image-2303" height="471" src="771999/mvc41.png" width="600" />

Set:

View Name = Index
View Engine = Razor

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

<img alt="MVC5" class="alignnone wp-image-2304" height="519" src="771999/mvc51.png" width="600" />

Copy and paste following code to the Index.cshtml.

@model MVCDemo.Models.CitiesViewModel

@{
    ViewBag.Title = &ldquo;Index&rdquo;;
}

<div style=&rdquo;font-family:Arial&rdquo;>
<h2>Index</h2>

<img alt="MVC6" class="alignnone wp-image-2305" height="272" src="771999/mvc61.png" width="600" />

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 &ldquo;No cities are selected&rdquo;;
    }
    else
    {
        StringBuilder sb = new StringBuilder();
        sb.Append(&ldquo;You selected &ndash; &ldquo; + string.Join(&ldquo;,&rdquo;, selectedCities));
        return sb.ToString();
    }
}

<img alt="MVC7" class="alignnone wp-image-2306" height="215" src="771999/mvc72.png" width="600" />

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

<img alt="MVC8" class="alignnone wp-image-2307" height="328" src="771999/mvc81.png" width="600" />

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.

<img alt="MVC9" class="alignnone wp-image-2308" height="286" src="771999/mvc91.png" width="600" />

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

No cities are selected

<img alt="MVC10" class="alignnone wp-image-2309" height="304" src="771999/mvc101.png" width="600" />

<img alt="MVC11" class="alignnone wp-image-2310" height="293" src="771999/mvc111.png" width="600" />

Reference

<img alt="" border="0" src="http://feeds.wordpress.com/1.0/comments/blogdotbesttechnologydotcom.wordpress.com/2286/" /> <img alt="" border="0" height="1" src="http://stats.wordpress.com/b.gif?host=besttechnologyblog.com&blog=58485837&post=2286&subd=blogdotbesttechnologydotcom&ref=&feed=1" width="1" />

License

This article has no explicit license attached to it but may contain usage terms in the article text or the download files themselves. If in doubt please contact the author via the discussion board below.

A list of licenses authors might use can be found here