Bind CheckBox In ASP.NET MVC 4

Here are the steps, 

Open Sql Server and Create a table name tblSports,here is the query to Create a table

  1. Create table tblSports  
  2. (  
  3.    Id int identity not nullName varchar(50), IsSelected bit  
  4. )  

Here there are three columns Id is identity column it is autoincremented column,Name column will contain name of Sports and IsSelected which has data type bit which will store values 0 or 1,if value is 0 then that sport will not be selected on view and if value is 1 then that sport will be selected by default when page loads.

Second step is to insert some dummy data into the table,here is the script to insert data

  1. insert into tblSports (Name,IsSelected) values ('Cricket',0)  
  2. insert into tblSports (Name,IsSelected) values ('Football',0)  
  3. insert into tblSports (Name,IsSelected) values ('Tennis',1)  
  4. insert into tblSports (Name,IsSelected) values ('Badminton',0)  

Third step is to create a store procedure which will select Id,Name and IsSelected column value from tblSports table.Here is the stored procedure

  1. Create PROCEDURE SpInsertUpdateDeleteMVC(@Para varchar(50) = '')  
  2. AS  
  3. BEGIN  
  4. If @Para = 'SelectForChkBox'  
  5. Begin  
  6. Select Id, Name, IsSelected from tblSports  
  7. End  
  8. END  

Now open visual studio,select File-New-Project and Select Asp.Net MVC4 Web Application from template and give a name to it as BindCheckBoxUsingMVC as shown and click ok


Select Empty template and View engine as Razor as shown in the figure


Now right click on the Models folder in solutions explorer and click add-new item-select code from template-select class and add a class,name it as DbAccess as shown in figure,

 

In the same way again right click on Models folder and add a new class file,name it as Sports.cs and write the following code in it

  1. public class Sports {  
  2.     public int Id {  
  3.         get;  
  4.         set;  
  5.     }  
  6.     public string Name {  
  7.         get;  
  8.         set;  
  9.     }  
  10.     public bool IsSelected {  
  11.         get;  
  12.         set;  
  13.     }  
  14.     public List < Sports > sportList {  
  15.         get;  
  16.         set;  
  17.     }  
  18. }  

This Model contains 4 properties Id which is the Id of Sport,Name will contain Sport Name,IsSelected which has datatype bool which will store value true or false.If value is true then by default sport will be selected,if value is false then by default sport will not be selected.Fourth property is sportList to which list of sports which will contain each sport Id,Name and IsSelected value will be assigned.This values we will fetch from database.

Now right click on controller folder and select add-controller and add a new Empty MVC Controller and name it as Home Controller as shown in figure

 

Now open web.config and add a connection string inside web.config as shown inside connectionStrings tag.
  1. <connectionStrings>  
  2.     <add name="dbConnect" providerName="System.Data.SqlClient" connectionString="Data Source=LIVINGROOM\SQLEXPRESS;Initial Catalog=codefirstDB;Integrated Security=true;" />   
  3. </connectionStrings>  
Here Data Source is Server Name and Initial Catalog is database Name.

Now open DbAccess Class and write following code in it

  1. public class DbAccess {  
  2.     SqlConnection con = new SqlConnection(ConfigurationManager.ConnectionStrings["dbConnect"].ToString());  
  3.     SqlCommand cmd = null;  
  4.     public List < Sports > SportList() {  
  5.         List < Sports > sport = new List < Sports > ();  
  6.         using(cmd = new SqlCommand("SpInsertUpdateDeleteMVC", con)) {  
  7.             cmd.CommandType = CommandType.StoredProcedure;  
  8.             cmd.Parameters.AddWithValue("@Para""SelectForChkBox");  
  9.             if (con.State.Equals(ConnectionState.Closed)) con.Open();  
  10.             SqlDataReader dr = cmd.ExecuteReader();  
  11.             while (dr.Read()) {  
  12.                 Sports st = new Sports();  
  13.                 st.Id = Convert.ToInt32(dr["Id"]);  
  14.                 st.Name = dr["Name"].ToString();  
  15.                 st.IsSelected = Convert.ToBoolean(dr["IsSelected"]);  
  16.                 sport.Add(st);  
  17.             }  
  18.             con.Close();  
  19.         }  
  20.         return sport;  
  21.     }  
  22. }  

The DbAccess class contains method SportList which will return the list of sports.An object of type List<Sports> is been created and to that each sport Id,Name,IsSelected value is added.First Line of the DbAccess class contains the name of connectionstring which we have given in web.config

Now open home controller and write following code in it.

  1. public ActionResult Index() {  
  2.     DbAccess db = new DbAccess();  
  3.     Sports spt = new Sports();  
  4.     spt.sportList = db.SportList().ToList();  
  5.     return View(spt);  
  6. }  

Add the namespace using BindCheckBoxUsingMVC.Models on the top.As this namespace contains DbAccess and Sports Class.

The controller contains Index method,in that I have created object of DbAccess class and Sports class,using Sports class object,sportList property has been assigned the List of Sports,which SportList method returns which is present in DbAccess class.To the return view I have passed the Sports Model object.Now right click on return View,select Add View and create a strongly typed View,Name it as Index View as shown in figure.Select Model Class as Sports.

 

Write the following code on the View

  1. @model BindCheckBoxUsingMVC.Models.Sports  
  2. @for(int i = 0; i < Model.sportList.Count; i++)  
  3. {  
  4.     @Html.HiddenFor(x => x.sportList[i].Id)  
  5.     @Html.HiddenFor(x => x.sportList[i].Name)  
  6.     @Html.CheckBoxFor(x => x.sportList[i].IsSelected)  
  7.     @Html.DisplayFor(x => x.sportList[i].Name)  
  8. }  

sportList is the property in Sports Model which will contain all the Sports values there Id,Name and IsSelected

I have used HiddenFor html helpers which contain Id,Name of Each Sport.This Id,Name property can be accessed inside controller method while posting the data,or if we want to display selected sport Id and Name.

Next I have used CheckBoxFor Html helper,to it I have passed bool property IsSelected.It will keep sport which has IsSelected value true selected by default and rest will be unselected.

Next helper is DisplayFor which will display Name of Each Sport

Build and run the application by setting default controller as Home and action name as Index,inside MapRoute method in RouteConfig class in App_Start folder.

Here is how the final output will be when we run the application


By Default Tennis will be Selected as it has IsSelected value set to 1.

X

Build smarter apps with Machine Learning, Bots, Cognitive Services - Start free.

Start Learning Now