Delete Confirm with Bootstrap modal in Asp.Net MVC

20,575

Solution 1

The modal this way has the same ID, no matter which data you try to delete. So just add a variable to specify different ID for the mmodal:

 using (Html.BeginForm("Delete", "RepFilters", new { id = item.ID }))
 {
 var myModal = "myModal" + item.ID;
 <tr>
    <td>...</td>
    <td>...</td>
     <button type="button" class="btn btn-danger btn-sm" data-toggle="modal" data-target="#@myModal">Delete</button>
     <!-- Modal -->
<div class="modal fade" id="@myModal" tabindex="-1" role="dialog" data-keyboard="false" aria-labelledby="myModalLabel">
    <div class="modal-dialog modal-sm">
     ...........<!--And the rest of the modal code-->

Solution 2

There are actually quite a few things you may want to address in your view. You are looping through the items in your model, and creating a separate form (and modal)for each item. This is probably not ideal, however if you really want to do it this way you can add a reference to the item id within the html for the modal. Just add a hidden input and set it's value to item.id.

However, I would not recommend this approach. I'm not certain for your reasons on wanting to shy away from JavaScript, but the functionality you want to create here is actually pretty basic.

See this post: Confirm delete modal/dialog with Twitter bootstrap?

Edit:

@foreach (var item in Model)
{    
<tr>
    <td>@index</td>
    <td>
        @Html.DisplayFor(modelItem => item.Description)
    </td>
    <td>
        @Html.DisplayFor(modelItem => item.Report.Description)
    </td>
    <td>
        @Html.ActionLink("Edit", "Edit", new { id = item.ID }) |
        @Html.ActionLink("Details", "Details", new { id = item.ID }) |
        <button type="button" class="btn btn-danger btn-sm" data-item-id="@item.ID" data-item-description="@item.Report.Description" data-toggle="modal" data-target="#confirm-delete">Delete</button>                
    </td>
</tr>    
}

<div class="modal fade" id="confirm-delete" tabindex="-1" role="dialog" aria-labelledby="myModalLabel">
<div class="modal-dialog modal-sm" role="document">
    <div class="modal-content">
        <div class="modal-header">
            <button type="button" class="close" data-dismiss="modal" aria-label="Close"><span aria-hidden="true">&times;</span></button>
            <h4 class="modal-title" id="myModalLabel">Confirm Delete</h4>
        </div>
        <div class="modal-body">
            Are you sure you want to delete: <span class="description"></span>
        </div>
        <div class="modal-footer">
            <button type="button" class="btn btn-default" data-dismiss="modal">Close</button>
            <input type="submit" value="Delete" class="btn btn-danger" />
        </div>
    </div>
</div>

<script>
$('#confirm-delete').on('click', '.btn-ok', function(e) {
    var $modalDiv = $(e.delegateTarget);
    var id = $(this).data('itemId');        
    $modalDiv.addClass('loading');
    $.post('/RepFilters/Delete/' + id).then(function () {
        $modalDiv.modal('hide').removeClass('loading');
    });
});
$('#confirm-delete').on('show.bs.modal', function(e) {
    var data = $(e.relatedTarget).data();
    $('.description', this).text(data.itemDescription);
    $('.btn-ok', this).data('itemId', data.itemId);
});
</script>

Solution 3

You first write a delete function in jquery .for displaye confirm message you can use sweetalert and write a custom file for sweetalert.

yo must add refrence sweetalert css and script in your view page.

function Delete(id) {
           var submitdelete=function(){  $.ajax({
                    url: '@Url.Action("/mycontroller/Delete)',
                    type: 'Post',
                    data: { id: id }
                })
                .done(function() {
                    $('#' + id).remove();//if you want to delete table row
                   msgBox.success("Success","Ok");
               });}
            msgBox.okToContinue("warning", "Are you sure to delete ?", "warning", "ok","cancel", submitdelete);

        }

Confirm dialog

  
var msgBox = {
    message: {
        settings: {
            Title: "",
            OkButtonText: "",
            type:"info"
        }
    },
    okToContinue: function(title, text, type, okButtonText,closeButtonText, isConfirmDo) {
        swal({
                title: title,
                text: text,
                type: type,
                showCancelButton: true,
                confirmButtonClass: 'btn-danger',
                confirmButtonText: okButtonText,
                cancelButtonText: closeButtonText,
                closeOnConfirm: false,
                closeOnCancel: true
            },
            function(isConfirm) {
                if (isConfirm) {

                    isConfirmDo();
                }
            });
    },
   
    confirmToContinue: function(title, text, type, confirmButtonText, cancelButtonText, isConfirmDo, isNotConfirmDo, showLoader) {
        if (!showLoader) {
            showLoader = false;
        }

        swal({
                title: title,
                text: text,
                type: type,
                showCancelButton: true,
                confirmButtonColor: "#DD6B55",
                confirmButtonText: confirmButtonText,
                cancelButtonText: cancelButtonText,
                closeOnConfirm: true,
                closeOnCancel: true,
                showLoaderOnConfirm: showLoader

            },
            function(isConfirm) {
                if (isConfirm) {
                    isConfirmDo();
                }
            });
    } ,

    success: function (title, text,okButtontex) {
        
        swal({
            title: title,
            text: text,
            type: "success",
            confirmButtonText: okButtontex
        });

    },
    info: function (title, text) {

        swal({
            title: title,
            text: text,
            type: "info",
            confirmButtonText: "OK"
        });

    },
    warning: function (title, text) {

        swal({
            title: title,
            text: text,
            type: "warning",
            confirmButtonText: "OK"
        });

    },
    error: function (title, text) {

        swal({
            title: title,
            text: text,
            type: "error",
            confirmButtonText: "OK"
        });

    },

}


 

Solution 4

Here's an easy way to do this. You should be able to adapt what i did here to your case. This requires very little javascript code.

<script>
    var path_to_delete;
    var root = location.protocol + "//" + location.host;

    $("#deleteItem").click(function (e) {
        path_to_delete = $(this).data('path');
        $('#myform').attr('action', root + path_to_delete);
    });
</script>
<table class="table table-hover" id="list">
    <thead class="bg-dark text-white">
        <tr>

            <th>
                Edit
            </th>
            <th>
                Employee
            </th>
            <th>
                Effective Date
            </th>
            <th>
                ST/OT/DT
            </th>
            <th>
                Other Pay
            </th>
            <th>
                Job
            </th>
            <th>
                Pending?
            </th>
            <th>
                Delete
            </th>
        </tr>
    </thead>
    <tbody>
        @foreach (var item in Model)
        {
            <tr>
                <td>
                    <a class="btn btn-sm" href="~/Employees/TerminationEdit/@item.Employee_Termination_Info_Id">
                        <i class="fa fa-lg fa-pencil-alt text-dark"></i>
                    </a>
                </td>
                <td>
                    @Html.DisplayFor(modelItem => item.Employee_Name_Number)
                </td>
                <td>
                    @Html.DisplayFor(modelItem => item.Effective_Date)
                </td>
                <td>
                    @Html.DisplayFor(modelItem => item.Employee_Time)
                </td>
                <td>
                    @Html.DisplayFor(modelItem => item.Employee_Other_Pay)
                </td>
                <td>
                    @Html.DisplayFor(modelItem => item.Job_Name)
                </td>
                <td>
                    @Html.DisplayFor(modelItem => item.Pending)
                </td>
                <td>
                    <a id="deleteItem" class="btn btn-sm" data-toggle="modal" data-target="#deleteModal"
                       data-path="/Employees/TerminationDelete/@item.Employee_Termination_Info_Id">
                        <i class="fa fa-lg fa-trash-alt text-danger"></i>
                    </a>
                </td>
            </tr>
        }
    </tbody>
</table>


<!-- Logout Modal-->
<div class="modal fade" id="deleteModal" tabindex="-1" role="dialog" aria-labelledby="exampleModalLabel" aria-hidden="true">
    <div class="modal-dialog" role="document">
        <div class="modal-content">
            <div class="modal-header">
                <h5 class="modal-title" id="exampleModalLabel">Are you sure?</h5>
                <button class="close" type="button" data-dismiss="modal" aria-label="Close">
                    <span aria-hidden="true">×</span>
                </button>
            </div>
            <div class="modal-body">Are you sure you want to delete this termination record? <br /><span class="text-danger">This cannot be undone.</span></div>
            <div class="modal-footer">
                <button class="btn btn-secondary" type="button" data-dismiss="modal">Cancel</button>
                @using (Html.BeginForm("TerminationDelete", "Employees", FormMethod.Post, new { id = "myform", @class = "" }))
                {
                    @Html.AntiForgeryToken()
           
                    <input type="submit" value="Delete" id="submitButton" class="btn btn-danger" />
                }
            </div>
        </div>
    </div>
</div>

So what happens here, is that the page will cycle through the model and draw the delete button (using font awesome). Note that here is is setting the data-path attribute for later use. When the button is clicked, it sets the form action for the button on the modal popup immediately. This is important, since it has a form around the delete button, it will send it to a POST and not a GET, as Rasika and Vasil Valchev pointed out. Plus, it has the benefit of the anti-forgery token.

Share:
20,575
Arianit
Author by

Arianit

Updated on March 15, 2020

Comments

  • Arianit
    Arianit over 4 years

    I am trying to make a dialog with bootstrap modal to confirm a delete. The delete works well, except it doesn't get the data which I select but it gets the first data in ID order from the database. I am new on client-side programming, so if someone could help me it would be nice.

    The code is:

    [HttpPost]
    public async Task<ActionResult> Delete(int id)
    {
         RepFilter repFilter = await db.RepFilters.FindAsync(id);
         db.RepFilters.Remove(repFilter);
         await db.SaveChangesAsync();
         return RedirectToAction("Index");
    }
    
    
    (razor)
    @foreach (var item in Model)
    {
       using (Html.BeginForm("Delete", "RepFilters", new { id = item.ID }))
       {
         <tr>
            <td>@index</td>
            <td>
               @Html.DisplayFor(modelItem => item.Description)
            </td>
            <td>
               @Html.DisplayFor(modelItem => item.Report.Description)
            </td>
            <td>
              @Html.ActionLink("Edit", "Edit", new { id = item.ID }) |
              @Html.ActionLink("Details", "Details", new { id = item.ID }) |
              <button type="button" class="btn btn-danger btn-sm" data-toggle="modal" data-target="#myModal">Delete</button>
             <!-- Modal -->
             <div class="modal fade" id="myModal" tabindex="-1" role="dialog" aria-labelledby="myModalLabel">
              <div class="modal-dialog modal-sm" role="document">
               <div class="modal-content">
                <div class="modal-header">
                 <button type="button" class="close" data-dismiss="modal" aria-label="Close"><span aria-hidden="true">&times;</span></button>
                  <h4 class="modal-title" id="myModalLabel">Confirm Delete</h4>
                </div>
               <div class="modal-body">Are you sure you want to delete: <span><b>@item.Description</b></span>
               </div>
               <div class="modal-footer">
                 <button type="button" class="btn btn-default" data-dismiss="modal">Close</button>
                 <input type="submit" value="Delete" class="btn btn-danger" />
               </div>
              </div>
              </div>
             </div>
            </td>
           </tr>
    
                }
            }
     </tbody>
    

    The button that opens the modal is getting the right ID, but the modal doesn't!

    So how to make the modal take the adequate data to delete?

    I am trying to avoid writing javascript and use data attributes, until there is no other choice