Share via

Working with Checkboxes in MVC

Kmcnet 1,356 Reputation points
2026-03-12T20:43:38.14+00:00

Hello everyone and thanks for the help in advance. I am refactoring an old webforms application to MVC. The page build the list of checkboxes from a database. The application then needs to check to see if the page has submitted any previous checkbox data in another database table. If data is present, the specific boxes need to be checked. So I am trying to figure out how to accomplish this. The model for the checkbox table looks like:

    public class tblCheckboxes
    {
        public string? Code { get; set; }
        public string? Description { get; set; }
        public string? Category { get; set; }
        public string? Display { get; set; }
    }

I want to have the label for the checkbox have the code and description. I'm really not sure how to conditionally check boxes if previous data was posted. Any help would be appreciated.

Developer technologies | ASP.NET | ASP.NET Core

2 answers

Sort by: Most helpful
  1. Jack Dang (WICLOUD CORPORATION) 16,515 Reputation points Microsoft External Staff Moderator
    2026-03-13T04:31:37.7266667+00:00

    Hi @Kmcnet ,

    Thanks for reaching out.

    In your case, I would suggest creating a ViewModel that holds both the checkbox data and a property to track if it should be checked. For example:

    public class CheckboxViewModel
    {
        public string Code { get; set; } = "";
        public string Description { get; set; } = "";
        public bool IsChecked { get; set; } = false; // tracks if the box should be checked
    }
    

    Then in the controller, load all checkbox items from your main table and the previous selections from the user’s table. Map them into the ViewModel so that IsChecked is true for items already selected:

    var allCheckboxes = _db.tblCheckboxes.ToList();
    var previousSelections = _db.tblUserCheckboxes
                                .Where(x => x.UserId == userId)
                                .Select(x => x.Code)
                                .ToList();
    
    var model = allCheckboxes.Select(c => new CheckboxViewModel
    {
        Code = c.Code ?? "",
        Description = c.Description ?? "",
        IsChecked = previousSelections.Contains(c.Code)
    }).ToList();
    
    return View(model);
    

    In the view, you can use a for loop to bind each checkbox to the IsChecked property and display the code and description:

    @model List<CheckboxViewModel>
    
    <form asp-action="SaveUserSelections" method="post">
        @for (int i = 0; i < Model.Count; i++)
        {
            <div>
                <input type="checkbox" asp-for="@Model[i].IsChecked" />
                <label>@Model[i].Code - @Model[i].Description</label>
                <input type="hidden" asp-for="@Model[i].Code" />
            </div>
        }
        <button type="submit">Save</button>
    </form>
    

    When posting back, you can filter the model for IsChecked = true and update the user’s table accordingly:

    [HttpPost]
    public IActionResult SaveUserSelections(List<CheckboxViewModel> model, int userId)
    {
        var existing = _db.tblUserCheckboxes.Where(x => x.UserId == userId);
        _db.tblUserCheckboxes.RemoveRange(existing);
    
        var selected = model.Where(x => x.IsChecked)
                            .Select(x => new tblUserCheckboxes
                            {
                                UserId = userId,
                                Code = x.Code
                            }).ToList();
    
        _db.tblUserCheckboxes.AddRange(selected);
        _db.SaveChanges();
    
        return RedirectToAction("EditUserSelections", new { userId });
    }
    

    Note: The code snippets I provided are for reference purposes. You should modify them as needed to fit your project structure, database schema, and specific business logic.

    If you found my response helpful or informative in any way, I would greatly appreciate it if you could follow this guidance provide feedback. 

    Thank you.


  2. Q&A Assist
    2026-03-12T20:43:56.9833333+00:00
    AI generated content. This question contains an answer created with AI from Q&A Assist. Learn more

    Use a view model plus a collection of “assigned” flags, then render checkboxes whose checked state is driven by that data, similar to how course assignments are handled for instructors.

    1. Create a view model that includes the checkbox data and whether each one is selected:
    public class CheckboxItemViewModel
    {
        public string Code { get; set; }
        public string Description { get; set; }
        public bool Assigned { get; set; }   // true if previously selected
    }
    
    public class CheckboxPageViewModel
    {
        public List<CheckboxItemViewModel> Items { get; set; }
    }
    
    1. In the controller GET action, load all checkbox definitions and the previously saved selections, then mark Assigned accordingly. This follows the same pattern as the AssignedCourseData example:
    public ActionResult Edit()
    {
        // All possible checkboxes from tblCheckboxes
        var allCheckboxes = db.tblCheckboxes.ToList();
    
        // Previously selected codes from another table
        var previouslySelectedCodes = new HashSet<string>(
            db.PreviousSelections
              .Where(x => x.UserId == currentUserId)
              .Select(x => x.Code));
    
        var model = new CheckboxPageViewModel
        {
            Items = allCheckboxes.Select(c => new CheckboxItemViewModel
            {
                Code = c.Code,
                Description = c.Description,
                Assigned = previouslySelectedCodes.Contains(c.Code)
            }).ToList()
        };
    
        return View(model);
    }
    
    1. In the view, render a checkbox for each item. The Assigned property controls whether the checkbox is checked when the page loads, just like the Assigned flag in AssignedCourseData:
    @model CheckboxPageViewModel
    
    @for (int i = 0; i < Model.Items.Count; i++)
    {
        <div>
            <input type="checkbox"
                   name="Items[@i].Assigned"
                   value="true"
                   @(Model.Items[i].Assigned ? "checked=\"checked\"" : "") />
            <input type="hidden" name="Items[@i].Assigned" value="false" />
            <input type="hidden" name="Items[@i].Code" value="@Model.Items[i].Code" />
            <span>@Model.Items[i].Code - @Model.Items[i].Description</span>
        </div>
    }
    

    This is analogous to the tutorial pattern where:

    • A view model (AssignedCourseData) carries CourseID, Title, and Assigned.
    • The controller populates Assigned based on existing relationships.
    • The view renders a checkbox list where the checked attribute is set for items with Assigned == true.
    1. In the POST action, read the posted model and save the selected codes. The model binder will populate Items[i].Assigned based on which checkboxes were checked.
    [HttpPost]
    public ActionResult Edit(CheckboxPageViewModel model)
    {
        var selectedCodes = model.Items
                                 .Where(i => i.Assigned)
                                 .Select(i => i.Code)
                                 .ToList();
    
        // Persist selectedCodes to the database as needed
    
        // ... save logic ...
    
        return RedirectToAction("Index");
    }
    

    This pattern gives a dynamic checkbox list whose checked state is driven by previously stored data, matching the approach used for course assignments in the referenced MVC + EF tutorials.


    References:

Your answer

Answers can be marked as 'Accepted' by the question author and 'Recommended' by moderators, which helps users know the answer solved the author's problem.