How can I reflect a boolean value in a checkbox state and update the boolean value when the checked state changes?

Russell Sharp 1 Reputation point
2021-08-07T21:48:03.72+00:00

I need to display boolean field values in a window when a database record is retrieved.
I also need to allow the boolean value to be changed and saved when the checkbox checked state is changed.

Developer technologies ASP.NET ASP.NET Core
{count} votes

1 answer

Sort by: Most helpful
  1. Anonymous
    2021-08-14T09:21:35.647+00:00

    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.

    123554-1.gif

    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:

    123254-image.png

    123291-javascript.txt

    The result as below: after clicking the checkbox, it will call the action method and update the entity.
    123534-2.gif


    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

    0 comments No comments

Your answer

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