In this article I will explain with an example, how to display multiple CheckBoxes with Checked Unchecked values in ASP.Net MVC Razor.
The CheckBoxes along with their checked or unchecked (selected) values will be populated from SQL Server database using Entity Framework in ASP.Net MVC Razor.
Database
I have made use of the following table Hobbies with the schema as follows.
I have already inserted few records in the table.
Note: You can download the database table SQL by clicking the download link below.
Creating an Entity Data Model
Namespaces
You will need to import the following namespace.
using System.Collections.Generic;
Controller
The Controller consists of the following Action method.
Action method for handling GET operation
Inside this Action method, first the records from the database are fetched using Entity Framework.
Finally, the Generic list of Hobbies is returned to the View.
public class HomeController : Controller
{
// GET: Home
public ActionResult Index()
{
using (HobbiesEntities entities = new HobbiesEntities())
{
return View(entities.Hobbies.ToList());
}
}
}
View
Inside the View, in the very first line the Generic list of Hobby class is declared as Model for the View.
Then a loop is executed over the Generic list of Hobby class objects and an HTML Table is generated consisting of a CheckBox and a Label.
The CheckBox will be checked or unchecked based on the value of the IsSelected property.
@model List<Hobby>
@{
Layout = null;
}
<!DOCTYPE html>
<html>
<head>
<meta name="viewport" content="width=device-width"/>
<title>Index</title>
</head>
<body>
<table border="0" cellpadding="0" cellspacing="0">
<tr>
<th></th>
<th>Hobby</th>
</tr>
@foreach (Hobby hobby in Model)
{
<tr>
<td>
@Html.CheckBoxFor(m => hobby.IsSelected)
</td>
<td>
@Html.DisplayFor(m => hobby.Description)
</td>
</tr>
}
</table>
</body>
</html>
Screenshot
Downloads