Search code examples
javascriptc#jqueryasp.net-mvcbootstrap-4

Passing "Id" selected checkbox to Modal bootstrap and send to controller


I have a list of Articles and I want to have a possibility to delete selected articles or all articles in a modal popup window. Also, I have checkboxes in my View. My idea - get an "Id" of each selected article, passing these articles to modal bootstrap popup. After, using form-action Post will send these "Id" to action controller method for further actions. (public ActionResult DeleteArticle (FormCollection fc){}).

I want to understand how I can pass "Id" of selected with checkboxes Articles to modal Bootstrap popup. Thanks!

enter image description here

My ListOfArticls.cshtml:

            <table class="table table-striped table-hover">
                <thead>
                    <tr>
                        <th>
                            <span class="custom-checkbox">
                                <input type="checkbox" id="checkBoxAll">
                                <label for="selectAll"></label>
                            </span>
                        </th>
                        <th>@Html.DisplayNameFor(model => model.Title)</th>
                        <th>@Html.DisplayNameFor(model => model.PublishDate)</th>
                        <th>@Html.DisplayNameFor(model => model.Tag)</th>
                        <th>@Html.DisplayNameFor(model => model.Note)</th>
                        <th>@Html.DisplayName("Category name")</th>
                    </tr>
                </thead>
                <tbody>

                    @foreach (var item in Model)
                    {
                        <tr>
                            <td>
                                <span class="custom-checkbox">
                                    <input type="checkbox" class="chkCheckBoxId" value="@item.Id">
                                    <label for="chkCheckBoxId"></label>
                                </span>
                            </td>
                            <td>
                                @Html.ActionLink(Html.DisplayFor(modelItem => item.Title).ToHtmlString(), "ArticleDetails", new { id = item.Id })
                            </td>
                            <td>
                                @Html.DisplayFor(modelItem => item.PublishDate)
                            </td>
                            <td>
                                @Html.DisplayFor(modelItem => item.Tag)
                            </td>
                            <td>
                                @Html.DisplayFor(modelItem => item.Note)
                            </td>
                            <td>
                                @Html.DisplayFor(modelItem => item.Category.Name)
                            </td>

                            <td>
                                <a href="#editArticleModal" class="edit" data-toggle="modal"><i class="material-icons" data-toggle="tooltip" title="Edit">&#xE254;</i></a>
                                <a href="#deleteArticleModal" class="delete" data-toggle="modal"><i class="material-icons" data-toggle="tooltip" title="Delete">&#xE872;</i></a>
                            </td>
                        </tr>
                    }

                </tbody>
            </table>
        <script type="text/javascript">
            $(document).ready(function () {
                $('#checkBoxAll').click(function () {
                    if ($(this).is(":checked")) {
                        $(".chkCheckBoxId").prop("checked", true)
                    }
                    else {
                        $(".chkCheckBoxId").prop("checked", false)
                    }
                });
            });
        </script>

Popup:

<!-- Delete Modal HTML -->
<div id="deleteArticleModal" class="modal fade">
    <div class="modal-dialog">
        <input type="hidden" id="linkId" />
        <div class="modal-content">
            <form action="@Url.Action("DeleteArticle", "Post")" method="post">
                <div class="modal-header">
                    <h4 class="modal-title">Delete Employee</h4>
                    <button type="button" class="close" data-dismiss="modal" aria-hidden="true">&times;</button>
                </div>
                <div class="modal-body">
                    <p>Are you sure you want to delete these Records?</p>
                    <p class="text-warning"><small>This action cannot be undone.</small></p>
                </div>
                <div class="modal-footer">
                    <input type="button" class="btn btn-default" data-dismiss="modal" value="Cancel" onclick="deleteConfirm()">
                    <input type="submit" class="btn btn-danger" value="Delete">
                </div>
            </form>
        </div>
    </div>
</div>

Controller:

        [HttpPost]
        public ActionResult DeleteArticle(FormCollection fc)
        { 
            // Some code
            return RedirectToAction("ListOfArticles");
        }

UPDATE:

Little bit corrected:

js

                    // loop through all the check boxes
                    $("input[type=checkbox]:checked").each(function () {

and my controller:

        [HttpPost]
        public ActionResult DeleteArticle(FormCollection fc)
        {
            var values = fc["articlesArray"];
            string[] str = values.Split(',');
            for(int i=0; i < str.Length; i++)
            {
                postService.DeleteArticleDTO(Int32.Parse(str[i]));
            }

            return RedirectToAction("ListOfArticles");
        }

Solution

  • If I understand this correctly, you want to multi-select through check boxes and clicking "Delete" on any of the row's delete buttons will open the popup with the ID's of the selected articles.

    You got this part correct; the checkbox input field with ID as its value.

    <input type="checkbox" class="chkCheckBoxId checkbox" value="@item.Id">
    

    Next what we want to do is loop through all the check boxes whenever the delete button is clicked.

    During the loop, we will identify which ones are checked and add them to the form tag of your modal.

    Add the new script below to your code, read the comments as well.

    <script type="text/javascript">
       $(document).ready(function () {
    
         $('#checkBoxAll').click(function () {
           if ($(this).is(":checked")) {
             $(".chkCheckBoxId").prop("checked", true)
           }else{
             $(".chkCheckBoxId").prop("checked", false)
           }
         });
    
         // bind this event to all delete buttons
         $(".delete").click(function(){
    
           // find the modal body
           var modal = $("#deleteArticleModal").find(".modal-body");       
    
           // loop through all the check boxes (class checkbox)
           $(".checkbox").each(function(index){
    
             // if they are checked, add them to the modal
             var articleId = $(this).val();
    
             if($(this).is(":checked")){
    
               // add a hidden input element to modal with article ID as value
               $(modal).append("<input name='articlesArray' value='"+articleId+"'  type='hidden' />")
             }
           });
         });
    
       });
    </script>
    

    In your form collection, the values will be passed with the property name articlesArray. It will be an array so be sure to loop through it with foreach.