Multiple Selection in ListBox with Checkbox in Asp.Net Core MVC, C#

How to create a listbox with checkbox for selection in asp.net core mvc using c#.net. Entity framework use to get data from DB and bind it to listbox.
In today's article will show a simple tutorial with example how to bind listbox with checkbox (Html.CheckBoxFor) for multi selection option from database (ms sql server) in asp.net core mvc using c#.net and how to get the selected value at controller end. Here I will use CheckBoxFor control. So for this article first we will create a table in database and add some records. 

Project table in sql

After this we will create a new asp.net core 8 mvc application using c#.net. Now add a model class file and add the below code.
  public class EmployeeModel
 {
     public List<EmpProjectDetail> ProjectDetailList { get; set; }
 }
 public class EmpProjectDetail
 {
     public bool IsProjectSelected { get; set; }
     public int Id { get; set; }
     public string ProjectName { get; set; }
 } 
In above code I have two class one for project detail and second to make the collection. This model class file we use in our view too bind the detail. Now let's add a controller file and add the below code. Before writing the code for HttpGet method make a connection with database in your asp.net core mvc application. Now add the below code.
[HttpGet]
public IActionResult Index()
{
    EmployeeModel employeeModel = new EmployeeModel();
    employeeModel.ProjectDetailList = new List<EmpProjectDetail>();
    //Db context
    EmployeeContext employeeContext = new EmployeeContext();
    var data = employeeContext.Projects.ToList();
    foreach (var item in data)
    {
        employeeModel.ProjectDetailList.Add(new EmpProjectDetail { Id = item.Id, ProjectName = item.ProjectName });
    }
    return View(employeeModel);
} 
In above code I have created the object of EmployeeModel class and after that created the object of list. Now creating the object of model class, we need to crate the object of DB context to pull the data from the database table. After getting the data I have moved all the data into the list. At the end the model class object has been passed to view Now create the view and add the below code in it.
@model EmployeeModel
@{
	ViewData["Title"] = "Index";

}
<style>
	.listboxstyle {
		height: 110px;
		width: 220px;
		overflow-y: auto;
		border-style: ridge;
	}
</style>
@using (Html.BeginForm("Index", "Home", FormMethod.Post))
{
	<div class="listboxstyle">
		<table width="200px">
			@for (int i = 0; i < Model.ProjectDetailList.Count; i++)
			{
				<tr>
					<td>
						@Html.CheckBoxFor(m => Model.ProjectDetailList[i].IsProjectSelected, new { @class = "form-check" })
						@Html.HiddenFor(m => Model.ProjectDetailList[i].Id)
						@Html.HiddenFor(m => Model.ProjectDetailList[i].ProjectName)
					</td>
					<td>
						<label for="@Model.ProjectDetailList[i].Id">@Model.ProjectDetailList[i].ProjectName</label>
					</td>
				</tr>
			}
		</table>
	</div>
	<br />
	<input type="submit" value="Submit" />
	<br />
	<span style="color:red;font-weight:bold;">@ViewBag.SelectedItem</span>
} 
In above code I have added the model class reference. Here check the css style. This is used for providing the listbox effect the end user. After that I have added form tag to post the form when user click on submit button.

After that I have used for looking to bind the controls. Here I have used Html.CheckBoxFor and Html.HiddenFor to place the data. Here I have used hidden control to maintain the value. One thing we need be very carefully check the after lambda expression the model value accessed. Why we need the value as in this format, because when we post the form at that time at controller end, we need the value. 

In last two lines I have added the input submit button and ViewBag to display the selected value at user end. Now let's create the HttpPost method at controller end. 
[HttpPost]
public IActionResult Index(EmployeeModel employeeModel)
{
    string selectedItem=string.Join(",", employeeModel.ProjectDetailList.Where(m=>m.IsProjectSelected==true).Select(m=>m.ProjectName));
    ViewBag.SelectedItem = "Your have selected: " + selectedItem;
    return View(employeeModel);
} 
In above code I have passed the EmployeeModel class as a parameter. In next line I have used LINQ query to get only those records which are having IsProjectSelected property value 'true' and at the end make the value comma separated. Finally passed it to ViewBag. Now lets run the code and check the output.
Listbox with Checkbox

Now select the value and click on Submit button. Out applied break point will hit. 

ListBox Selected Value

In above code we are getting the selected item. Now let's press F5 to check the final output.

Listbox Selected Value in View

Post a Comment