Hi @Russell Sharp ,
To show the boolean value in the View page, you could use the checkbox element and use asp-for
attribute to bind the value, code as below:
<input type="checkbox" class="chk" asp-for="@Model[i].IsSelected" data-id="@Model[i].DepId" />
More detail information, you can refer the Tag Helpers in ASP.NET Core.
Then, to update the boolean value, you can submit the form data to controller and update the value.
Please refer the following sample code:
Department model:
public class Department
{
[Key]
public int DepId { get; set; }
public string DepName { get; set; }
public Boolean IsSelected { get; set; }
}
Controller:
public class HomeController : Controller
{
private readonly ILogger<HomeController> _logger;
private readonly ApplicationDbContext _context;
public HomeController(ILogger<HomeController> logger, ApplicationDbContext context)
{
_logger = logger;
_context = context;
}
public IActionResult DepartmentIndex()
{
return View(_context.Departments.ToList());
}
[HttpPost]
public IActionResult UpdateDepartments(List<Department>
departments)
{
foreach(var item in departments)
{
_context.Departments.Where(c => c.DepId == item.DepId).FirstOrDefault().IsSelected = item.IsSelected;
}
_context.SaveChanges();
return RedirectToAction(nameof(DepartmentIndex));
}
View Page:
@model List<WebApplication1.Data.Department>
@{
ViewData["Title"] = "DepartmentIndex";
}
<form asp-action="UpdateDepartments">
<table class="table">
<thead>
<tr>
<th>
DepName
</th>
<th>
IsSelected
</th>
</tr>
</thead>
<tbody>
@for (var i = 0; i < Model.Count(); i++)
{
<tr>
<td>
<input type="hidden" class="depid" asp-for="@Model[i].DepId" />
<input type="text" class="depname" asp-for="@Model[i].DepName" />
</td>
<td>
<input type="checkbox" class="chk" asp-for="@Model[i].IsSelected" data-id="@Model[i].DepId" />
</td>
</tr>
}
</tbody>
</table>
<input type="submit" value="Submit" />
</form>
The result as below: after clicking the submit button, it will submit the form and udpate the entities.
Besides, if you want to change the boolean value after checked/unchecked the checkbox, you can use JQuery ajax to call the action method and update the relate entity.
Add the following action method:
[HttpPost]
public IActionResult UpdateSigleDepartment(Department department)
{
var dep = _context.Departments.Where(c => c.DepId == department.DepId).FirstOrDefault();
dep.IsSelected = department.IsSelected;
_context.SaveChanges();
return Json("Success");
}
Then, add the script at the end of the view page:
The result as below: after clicking the checkbox, it will call the action method and update the entity.
If the answer is helpful, please click "Accept Answer" and upvote it.
Note: Please follow the steps in our documentation to enable e-mail notifications if you want to receive the related email notification for this thread.
Best Regards,
Dillion