A set of technologies in the .NET Framework for building web applications and XML web services.
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.
- 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; }
}
- In the controller
GETaction, load all checkbox definitions and the previously saved selections, then markAssignedaccordingly. This follows the same pattern as theAssignedCourseDataexample:
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);
}
- In the view, render a checkbox for each item. The
Assignedproperty controls whether the checkbox is checked when the page loads, just like theAssignedflag inAssignedCourseData:
@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) carriesCourseID,Title, andAssigned. - The controller populates
Assignedbased on existing relationships. - The view renders a checkbox list where the
checkedattribute is set for items withAssigned == true.
- In the
POSTaction, read the posted model and save the selected codes. The model binder will populateItems[i].Assignedbased 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: