Click here to Skip to main content
Click here to Skip to main content

Tagged as

ASP.Net MVC – How to create a ListBox?

, 11 May 2014
Rate this:
Please Sign up or sign in to vote.
CodeProject 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. The SQL

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 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 following:

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 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 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 [HttpPostattribute.

[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 be appeared.

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: Arun Ramachandran (http://BestTEchnologyBlog.Com)


License

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

Share

About the Author

Arun Ramachandran India
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

 
-- There are no messages in this forum --
| Advertise | Privacy | Mobile
Web01 | 2.8.140827.1 | Last Updated 12 May 2014
Article Copyright 2014 by Arun Ramachandran India
Everything else Copyright © CodeProject, 1999-2014
Terms of Service
Layout: fixed | fluid