How to Bind Checkboxlist in mvc4

How to Bind Checkboxlist from database

Step 1:
 First you select checkbox data from database using following controller code. here HomeModel is model class . we can add data in list and then pass though viewbag from controller to view


            List<HomeModel> lst1 = new List<HomeModel>();
            HomeModel hm=new HomeModel();
            foreach ( System.Data.DataRow dr1 in dt1.Tables[0].Rows )
            {
                lst1.Add( new HomeModel { HobbyName = @dr1["HobbyName"].ToString(), HobbyId =int.Parse( @dr1["HobbyId"].ToString()) } );
            }
            ViewBag.Hobby = lst1;


Step 2 :
 Now you can display viewbag data in checkbox using foreach loop as following


@foreach (var item in @ViewBag.Hobby)
        {         
          <input type="checkbox" name="ips"  value="@item.HobbyName" />@item.HobbyName
        }           
         
Step 3 : when run application chechbox  are created dynamically as following

Mvc4 Checkbox



Previous
Next Post »