How to select all checkboxes and pass to controller

Viewed 455

I build this code for select all checboxes and pass to controller, I using button when click it check all checkboxes and pick up all variables like (idtip, idemployee) trought array send to controller to update database table.

            <tr>
            <th>name</th>
            <th>tips</th>
            <th>
                <button id="btnClick" class="btnClick">Select all</button>

            </th>
            </tr>

Here is my input and script.

        @foreach (var item in (IEnumerable<cit.Models.getCheIdTip_Result>)Model)
{
    <tr>
        <td>@item.idtip</td>
        <td>@item.tipname</td>
        <td>
            <div class="pure-checkbox" idtip="@item.idtip">
                  <input type="checkbox" idtip="@item.idtip" class="checktip" 
                  checked="@(item.idemployee == ViewBag.idemployee ? true : false)" 
                  name="@item.id.ToString()" id="@item.id.ToString()" />
                 <label for="@item.id.ToString()"></label>
            </div>
        </td>
    </tr>
}
</table>
    <input type="hidden" value="@ViewData["idemployee"]" name="idemployee" id="idemployee" class="idemployee" />
<script>
    $('.pure-checkbox').click(function () {
        $(this).parents('td').toggleClass('chked')
    })

    var wantedids = [idemployee,idtip]

    $("#btnClick").click(function () {
        for (var i = 0; i < $('.pure-checkbox').length; i++) {
            if ($('.pure-checkbox').eq(i).parents('td').hasClass('chked')) {
                wantedids.push(
                    $('.pure-checkbox').eq(i).attr('idtip')
                )
            }
        }
        $.post("UrlSettingsDocument.Tips", { ids: wantedids },

        )
    })
1 Answers

I using button when click it check all checkboxes and pick up all variables like (idtip, idemployee) trought array send to controller to update database table.

You could refer the following sample code:

  1. Create a ViewModel to display records:

     public class TestViewModel
     {
         public int id { get; set; }
         public int idtip { get; set; }
         public string idemployee { get; set; }
         public bool isChecked { get; set; }
     }
    
  2. In the Controller, add the following actions:

     //Set the initial data and return to view.
     public  IActionResult Default()
     {
         List<TestViewModel> items = new List<TestViewModel>()
         {
             new TestViewModel(){ id=101, idtip=1001, idemployee="AAA" },
              new TestViewModel(){id=102,idtip=1002, idemployee="BBB" },
               new TestViewModel(){id=103, idtip=1003, idemployee="CCC" },
                new TestViewModel(){ id=104,idtip=1004, idemployee="DDD" },
                 new TestViewModel(){id=105, idtip=1005, idemployee="EEE" }
         };
    
         ViewBag.idemployee = "CCC"; //set the default checked item.
         return View(items);
     }
    
     public IActionResult AddItems(IEnumerable<TestViewModel> items)
     {
         //insert the items into database.
         return Ok("OK");
     }
    
  3. Then, in the View page (Default.cshtml), using the following code to display the content:

    Here we can use a select all checkbox, after checking it, will select all items.

     @model IEnumerable<WebApplication.Models.TestViewModel> 
     @{
         ViewData["Title"] = "Default";
         Layout = "~/Views/Shared/_Layout.cshtml";
     }
    
     <table class="table">
         <thead>
             <tr>
                 <th>
                     <input type="checkbox" id="btnSelectAll" class="btnClick" /> <label for="btnSelectAll">Select All</label>
                 </th>
                 <th>
                     @Html.DisplayNameFor(model => model.idtip)
                 </th>
                 <th>
                     @Html.DisplayNameFor(model => model.idemployee)
                 </th>
                 <th>
    
                 </th>
             </tr>
         </thead>
         <tbody>
     @foreach (var item in Model) {
             <tr>
                 <td>
                     <div class="pure-checkbox" idtip="@item.idtip">
                         <input type="checkbox" idtip="@item.idtip" data-idemployee="@item.idemployee" class="checktip"
                                checked="@(item.idemployee == ViewBag.idemployee ? true : false)"
                                name="@item.id.ToString()" id="@item.id.ToString()" />
                         <label for="@item.id.ToString()"></label>
                     </div>
                 </td>
                 <td>
                     @Html.DisplayFor(modelItem => item.idtip)
                 </td>
                 <td>
                     @Html.DisplayFor(modelItem => item.idemployee)
                 </td>
                 <td>
                     @Html.ActionLink("Edit", "Edit", new { /* id=item.PrimaryKey */ }) |
                     @Html.ActionLink("Details", "Details", new { /* id=item.PrimaryKey */ }) |
                     @Html.ActionLink("Delete", "Delete", new { /* id=item.PrimaryKey */ })
                 </td>
             </tr>
     }
         </tbody>
     </table>
    
     <button id="btnSubmit" class="btnClick">Submit</button>
    

    At the end of the Default.cshtml page, using the following script to achieve the select all function and submit the records to the controller.

     @section Scripts{ 
         <script>
             $(function () {
                 //If checked the select all checkbox, select all items. else unchecked.
                 $("#btnSelectAll").click(function () {
                     if ($(this).is(":checked")) {
                         $(".checktip").each(function (index, item) {
                             $(item).prop("checked", true);
                         });
                     }
                     else {
                         $(".checktip").each(function (index, item) {
                             $(item).prop("checked", false);
                         });
                     }
                 });
    
                 $("#btnSubmit").click(function () {
                     var testViewModels = [];
                     //using the class selector to loop through the checkbox list and get all items, if you want to get the checked items, add an if...else statement in the each function.
                     $(".checktip").each(function (index, item) { 
                         var TestViewModel = {}; 
                         TestViewModel.idtip = $(this).attr("idtip");
                         TestViewModel.idemployee = $(this).attr("data-idemployee");
                         TestViewModel.isChecked = $(this).is(":checked");
                         testViewModels.push(TestViewModel);
                     });
    
                     $.ajax({
                         type: "Post",
                         url: "/Home/AddItems",  //remember change the controller to your owns. 
                         data: { items: testViewModels },  //the name ("items") should be the same with the parameter's name in the controller.
                         success: function (data) {
                             console.log(data) 
                         },
                         error: function (response) {
                             console.log(response.responseText);
                         }
                     });
                 });
    
             });
         </script>
     }
    

The result as below:

enter image description here

Related