在Asp.Net MVC中使用Bootstrap模态框进行删除确认

4

我想使用Bootstrap模态框来创建一个确认删除的对话框。删除功能已经可以正常工作,但是它没有获取到我所选择的数据,而是获取了数据库中ID排序后的第一条数据。由于我是客户端编程的新手,所以如果有人能够帮助我,那就太好了。

代码如下:

[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>
那么如何使模态框获取足够的数据来进行删除操作呢?
我正在尝试避免编写JavaScript代码,并使用数据属性,除非没有其他选择。
4个回答

2
实际上,您可能希望在您的视图中解决相当多的问题。您正在循环遍历模型中的项目,并为每个项目创建单独的表单(和模式)。这可能不是理想的方式,但是如果您真的想以这种方式做,可以在模态框的html中添加对该项id的引用。只需添加一个隐藏输入并将其值设置为item.id即可。
然而,我不建议采用这种方法。我不确定您想要避免JavaScript的原因,但您想要在此处创建的功能实际上非常基本。
请参阅此帖子:使用Twitter Bootstrap确认删除模态/对话框? 编辑:
@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>

你能用代码演示一下如何在Asp.Net MVC中实现吗? - Arianit
那么你的意思是使用JavaScript更好,而避免使用它不是一个好习惯? - Arianit
1
不,我不建议尝试避免使用JavaScript。 - Steve

2

这种方式的模态框无论您要删除哪些数据,其ID都是相同的。因此,只需添加一个变量来指定不同的ID以用于该模态框:

 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-->

1

这里有一种简单的方法来实现这个。你应该能够将我在这里做的适应到你的情况中。这只需要很少的JavaScript代码。

<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>

这里发生的是页面会循环模型并绘制删除按钮(使用font awesome)。请注意,在此处设置data-path属性以备后用。当点击按钮时,它会立即为模态弹出窗口上的按钮设置表单操作。这很重要,因为它有一个围绕该删除按钮的表单,它将其发送到POST而不是GET,正如Rasika和Vasil Valchev指出的那样。此外,它具有防伪令牌的好处。

1

你需要先在jQuery中编写一个删除函数。为了显示确认消息,可以使用sweetalert并编写自定义文件。

你必须在视图页面中添加sweetalert的CSS和脚本引用。

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);

        }

确认对话框

  
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"
        });

    },

}


 


但是在Bootstrap文档中提到,我可以避免使用JavaScript,而是使用数据属性。这就是我想找出哪个属性传递我需要的数据的原因。 - Arianit

网页内容由stack overflow 提供, 点击上面的
可以查看英文原文,
原文链接