A set of technologies in the .NET Framework for building web applications and XML web services.
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.