Here are the steps,
Open Sql Server and Create a table name tblSports,here is the query to Create a table
- Create table tblSports
- (
- Id int identity not null, Name varchar(50), IsSelected bit
- )
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
- insert into tblSports (Name,IsSelected) values ('Cricket',0)
- insert into tblSports (Name,IsSelected) values ('Football',0)
- insert into tblSports (Name,IsSelected) values ('Tennis',1)
- 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
- Create PROCEDURE SpInsertUpdateDeleteMVC(@Para varchar(50) = '')
- AS
- BEGIN
- If @Para = 'SelectForChkBox'
- Begin
- Select Id, Name, IsSelected from tblSports
- End
- 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
- public class Sports {
- public int Id {
- get;
- set;
- }
- public string Name {
- get;
- set;
- }
- public bool IsSelected {
- get;
- set;
- }
- public List < Sports > sportList {
- get;
- set;
- }
- }
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.
- <connectionStrings>
- <add name="dbConnect" providerName="System.Data.SqlClient" connectionString="Data Source=LIVINGROOM\SQLEXPRESS;Initial Catalog=codefirstDB;Integrated Security=true;" />
- </connectionStrings>
Here Data Source is Server Name and Initial Catalog is database Name.
Now open DbAccess Class and write following code in it
- public class DbAccess {
- SqlConnection con = new SqlConnection(ConfigurationManager.ConnectionStrings["dbConnect"].ToString());
- SqlCommand cmd = null;
- public List < Sports > SportList() {
- List < Sports > sport = new List < Sports > ();
- using(cmd = new SqlCommand("SpInsertUpdateDeleteMVC", con)) {
- cmd.CommandType = CommandType.StoredProcedure;
- cmd.Parameters.AddWithValue("@Para", "SelectForChkBox");
- if (con.State.Equals(ConnectionState.Closed)) con.Open();
- SqlDataReader dr = cmd.ExecuteReader();
- while (dr.Read()) {
- Sports st = new Sports();
- st.Id = Convert.ToInt32(dr["Id"]);
- st.Name = dr["Name"].ToString();
- st.IsSelected = Convert.ToBoolean(dr["IsSelected"]);
- sport.Add(st);
- }
- con.Close();
- }
- return sport;
- }
- }
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.
- public ActionResult Index() {
- DbAccess db = new DbAccess();
- Sports spt = new Sports();
- spt.sportList = db.SportList().ToList();
- return View(spt);
- }
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
- @model BindCheckBoxUsingMVC.Models.Sports
- @for(int i = 0; i < Model.sportList.Count; i++)
- {
- @Html.HiddenFor(x => x.sportList[i].Id)
- @Html.HiddenFor(x => x.sportList[i].Name)
- @Html.CheckBoxFor(x => x.sportList[i].IsSelected)
- @Html.DisplayFor(x => x.sportList[i].Name)
- }
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.