DEV Community

Sardar Mudassar Ali Khan
Sardar Mudassar Ali Khan

Posted on

CheckBoxList in asp net mvc

In ASP.NET MVC, you can use the CheckBoxList to create a list of checkboxes that allows users to select multiple items. However, please note that there is no built-in CheckBoxList control in ASP.NET MVC like in ASP.NET Web Forms. You'll need to create your own implementation or use a third-party library to achieve this functionality.

Here's an example of how you can create a CheckBoxList in ASP.NET MVC using a custom implementation:

  1. Create a ViewModel to represent the data for the checkboxes. For example:
public class CheckBoxViewModel
{
    public int Id { get; set; }
    public string Text { get; set; }
    public bool IsChecked { get; set; }
}
Enter fullscreen mode Exit fullscreen mode
  1. In your controller, populate a list of CheckBoxViewModel objects and pass it to the view. For example:
public ActionResult Index()
{
    List<CheckBoxViewModel> checkBoxes = new List<CheckBoxViewModel>
    {
        new CheckBoxViewModel { Id = 1, Text = "Checkbox 1", IsChecked = false },
        new CheckBoxViewModel { Id = 2, Text = "Checkbox 2", IsChecked = true },
        // Add more checkboxes as needed
    };

    return View(checkBoxes);
}
Enter fullscreen mode Exit fullscreen mode
  1. Create a view (.cshtml) to render the CheckBoxList. For example:
@model List<CheckBoxViewModel>

@using (Html.BeginForm())
{
    for (int i = 0; i < Model.Count; i++)
    {
        @Html.HiddenFor(m => m[i].Id)
        <div>
            @Html.CheckBoxFor(m => m[i].IsChecked)
            @Html.LabelFor(m => m[i].IsChecked, Model[i].Text)
        </div>
    }

    <input type="submit" value="Submit" />
}
Enter fullscreen mode Exit fullscreen mode
  1. Handle the form submission in your controller action. For example:
[HttpPost]
public ActionResult Index(List<CheckBoxViewModel> model)
{
    // Process the submitted checkboxes here

    return RedirectToAction("Index");
}
Enter fullscreen mode Exit fullscreen mode

This is a basic example to get you started with a custom implementation of CheckBoxList in ASP.NET MVC. Keep in mind that you might need to enhance this implementation based on your specific requirements. Alternatively, you can explore third-party libraries or extensions that provide a pre-built CheckBoxList control for ASP.NET MVC.

Top comments (1)

Collapse
 
adrobson profile image
Alistair Robson

Thanks. The checkboxlist was just what I needed.