How To Bind CheckBoxList In ASP.NET MVC

How To Bind CheckBoxList In ASP.NET MVC

In this article we will learn how to bind CheckBoxList in ASP.NET MVC, Here we have bind checkoxlist from database using sql server database and bind this data to razor view using viebag, because viewbag is dynamic type so we can’t need to type casting and easily binds list data using foreach loop.

Step 1: Create an MVC Application

Step 2: Add Model class

public class HomeModel
{
public int HobbyId{ get; set; }
public string HobbyName{ get; set; }

}

Step 3: Now add controller and action method for binding checkbox list data fro corresponding view or page,so we can pass these binding data to view using viewbag.

List lst1 = new List();
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 4: Now using foreach loop we have bind these viewbag data as below mentioned code in particular page using razor-view syntax.

@foreach (var item in @ViewBag.Hobby)
{
<input name=”ips” type=”checkbox” value=”@item.HobbyName” />@item.HobbyName
}

Now, you have try this code and run your web application, and have any query regarding How To Bind CheckBoxList In ASP.NET MVC, then feel free to comment on comment section

How To Bind CheckBoxList In ASP.NET MVC

SEE MORE

Leave a Reply

Your email address will not be published. Required fields are marked *