twitter-bootstrap 在 Asp.Net MVC 中使用 Bootstrap 模式删除确认

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/38310691/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me): StackOverFlow

提示:将鼠标放在中文语句上可以显示对应的英文。显示中英文
时间:2020-10-22 00:07:05  来源:igfitidea点击:

Delete Confirm with Bootstrap modal in Asp.Net MVC

asp.net-mvctwitter-bootstraprazorbootstrap-modal

提问by Arianit

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.

我正在尝试使用引导模式进行对话框以确认删除。删除效果很好,除了它没有获取我选择的数据,但它从数据库中获取 ID 顺序中的第一个数据。我是客户端编程的新手,所以如果有人可以帮助我,那就太好了。

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!

打开模态的按钮获得了正确的 ID,但模态却没有!

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

我试图避免编写 javascript 并使用数据属性,直到没有其他选择

采纳答案by Tinaira

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:

无论您尝试删除哪些数据,这种方式的模态都具有相同的 ID。所以只需添加一个变量来为 mmodal 指定不同的 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-->

回答by Steve

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.

在您看来,实际上有很多事情您可能想要解决。您正在遍历模型中的项目,并为每个项目创建一个单独的表单(和模态)。这可能并不理想,但是如果你真的想这样做,你可以在模态的 html 中添加对 item id 的引用。只需添加一个隐藏输入并将其值设置为 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.

但是,我不推荐这种方法。我不确定你想避开 JavaScript 的原因,但你想在这里创建的功能实际上是非常基本的。

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

请参阅此帖子:使用 Twitter 引导程序确认删除模式/对话框?

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>

回答by Geo Shmeo

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.

这是一个简单的方法来做到这一点。你应该能够根据你的情况调整我在这里所做的。这需要很少的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>

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.

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

回答by Zebra

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

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

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

您必须在您的视图页面中添加引用 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);

        }

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

    },

}