Bind CheckBox In ASP.NET MVC 4

Here are the steps, 

1. Open DataBase And Create a table tblSportsMaster.
  1. CREATE TABLE tblSportsMaster  
  2. (  
  3.    ID int IDENTITY(1,1) PRIMARY KEY,  
  4.    Sport varchar(100)  
  5. )   
2. Now write the following insert queries to insert some record in the table
  1. insert into tblSportsMaster (Sport) values ("Cricket");   
  2. insert into tblSportsMaster (Sport) values ("Football");  
  3. insert into tblSportsMaster (Sport) values ("Tennis");  
  4. insert into tblSportsMaster (Sport) values ("TableTennis");  
  5. insert into tblSportsMaster (Sport) values ("Badminton");   
3. Create a storedprocedure which will return the list of Sport from tblSportsMaster.
  1. Create PROCEDURE Select_Sports  
  2. (  
  3. @Para varchar(50)=''"  
  4. )  
  5. AS  
  6. BEGIN  
  7. If @Para = 'Select'  
  8. Begin  
  9. Select ID,Sport from tblSportsMaster  
  10. END  
  11. END  
4. Open visual studio 2010-Select File-New-Project and Select Asp.Net MVC4 Web Application - Give name to the application and click ok.Now Select Internet application and click ok

5. Right click on the project and Add new class Name it as DBData in which we will write DataBase Related Logic. Here is the Snapshot.

project

Thus we can see in DBData class there is one Method GetList which return type is DataTable which return datatable containing list of Sport which we will Bind to the CheckBox

6. Now right click on Model and Add new class Name it as SportsListChk and write the following code in it.
  1. public class SportsListChk  
  2. {  
  3.     public int ID  
  4.     {  
  5.         get;  
  6.         set;  
  7.     }  
  8.     public string Sport  
  9.     {  
  10.         get;  
  11.         set;  
  12.     }  
  13.     public bool IsChecked  
  14.     {  
  15.         get;  
  16.         set;  
  17.     }  
  18. }  
  19. public class ChkSportsList  
  20. {  
  21.     public List < SportsListChk > SportItems  
  22.     {  
  23.         get;  
  24.         set;  
  25.     }  
  26. }  
Here is the SnapShot.

SportItems

Thus we can see in the above we have two Class one is SportsLstChk which contains properties ID,Sport and IsChecked which are used to Bind to the Checkbox and Another Class ChkSportsList which contains List SportItems in which we will stored the above property values and return to View.

7. Now right click on the Controller folder and Add New Controller Name it as SportSelectionController here is the SnapShot.

Add controller

Click Add and your controller will be added.

8. In the controller do the following code:
  1. public ActionResult Index()  
  2. {  
  3.     DBData obj = new DBData();  
  4.     DataTable dt = new DataTable();  
  5.     dt = obj.GetList();  
  6.     ChkSportsList objList = new ChkSportsList();  
  7.     List < SportsListChk > objSports = new List < SportsListChk > ();  
  8.     for (int i = 0; i < dt.Rows.Count; i++)  
  9.     {  
  10.         objSports.Add(new SportsListChk()  
  11.         {  
  12.             ID = Convert.ToInt32(dt.Rows[i]["Id"].ToString()), Sport = dt.Rows[i]["Sport"].ToString(), IsChecked = false  
  13.         });  
  14.     }  
  15.     objList.SportItems = objSports;  
  16.     return View(objList);  
  17. }  
Here is the SnapShot.

code

Thus here I have written List objList to the View.Now Right Click on ActionResult Index and Add View and add a Strongly type View.

Here is the Snapshot,

Add view

Click Add.Do not forget to kept the Model Class Name as ChkSportsList,you can see in the Image.

9. On the View write the following Logic.
  1. @using(Html.BeginForm())  
  2. { < table >  
  3.      <tr >  
  4.         <td >  
  5.         @for(int i = 0; i < Model.SportItems.Count; i++)  
  6.         {  
  7.             @Html.CheckBoxFor(m => m.SportItems[i].IsChecked)  
  8.             @Model.SportItems[i].Sport  
  9.             @Html.HiddenFor(m => m.SportItems[i].ID)  
  10.         }   
  11.      </td> 
  12.    </tr> 
  13.  </table>  
  14. }  
Here is the SnapShot.

Snapshot

10. Now in the route.config in routes.MapRoute just set the Controller name to SportSelection and Action Name to Index.
  1. routes.MapRoute(  
  2. name: "Default",  
  3. url: "{controller}/{action}/{id}",  
  4.    defaults: new { controller = "SportSelection", action = "Index", id = UrlParameter.Optional }  
  5. );  
Here is the route.config Snapshot.

route.config

Build and run the Application the output will be:

Build and run

Do not forget to Add Connection String in the WebConfig.
  1. <connectionStrings>  
  2.    <add name="testCrud" connectionString="server=LIVINGROOM\SQLEXPRESS;database=practisedatabase;Integrated Security=true;Pooling=false;" />  
  3. </connectionStrings>  
So here is the way to bind the Data from DataBase to CheckBox in MVC4. I will come with more details in the next blog. If any thing is remaining or you found any other way please do let me know about it.