ASP.NET MVC – How to Create a ListBox?






4.42/5 (10 votes)
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 ListBox
es in ASP.NET MVC.
Let’s try to understand this with an example. We will be using tblCity
table for this.
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:
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.
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.
Copy and paste following code to the CitiesViewModel
class.
public class CitiesViewModel
{
public IEnumerable<string> SelectedCities { get; set; }
public IEnumerable<SelectListItem> Cities { get; set; }
}
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);
}
Then right click on the Index
action method in HomeController
and select Add View from the context menu.
Set:
View Name = Index
View Engine = Razor
Model class = CitiesViewModel(MVCDemo.Models)
and click Add.
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>
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();
}
}
Now run the application and we will get a screen like below:
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.
Without selecting any cities and clicking on Submit button, a message like below will be appeared as expected.
No cities are selected
Reference
- Arun Ramachandran (http://BestTEchnologyBlog.Com)