如何创建C#删除确认框

时间:2016-05-23 19:04:33

标签: javascript c# css asp.net-mvc twitter-bootstrap

当用户点击删除按钮时,我需要添加删除确认框。我怎么这么做?在删除代码运行之前的html页面或我的Controller调用中?或者可以自举吗?我输了。

这是我的按钮元素和我的控制器动作。

 <div class="row">
    <div class="col-md-6">
        <input type="submit" value="Save" class="btn btn-lg btn-primary" />
    </div>
    @if (!Model.IsNew)
    {
    <div class="col-md-6">
        <a href="@(Url.Action<UnitsController>(c => c.Delete(Model.Entity.Id)))" class="btn btn-primary col-md-offset-9 col-md-3 ">Delete</a>
    </div>
    }
</div>

控制器

public ActionResult Delete(int id)
{
    var record = DataAccessService.Get<Unit>(id);

    DataAccessService.Delete(record);
    DataAccessService.Save();
    return RedirectToAction<UnitsController>(u => u.Index());
}

2 个答案:

答案 0 :(得分:2)

您可以使用confirm的Javascript,它会在浏览器上显示消息后返回bool值,或者使用css bootstrap,因为您已在应用程序中显示该消息。

确认Javascript

只需在onclick标记的a事件中添加确认即可。样本:

<a href="@(Url.Action<UnitsController>(c => c.Delete(Model.Entity.Id)))" 
   class="btn btn-primary col-md-offset-9 col-md-3" 
   onclick="return confirm('Are you sure you want to delete this item?')">Delete</a>

CSS Bootstrap

由于你使用的是css bootstrap,你可以尝试不带问题。样品。

定义模态窗口的css标记

<div id="deleteConfirm" class="modal">
    <div class="modal-dialog">
        <div class="modal-content">
            <div class="modal-header">
                <button type="button" class="close" data-dismiss="modal" aria-hidden="true">&times;</button>
                <h4 class="modal-title">Delete Entity</h4>
            </div>
            <div class="modal-body">
                <p>Are you sure you want to delete this item?</p>
            </div>
            <div class="modal-footer">
                <button type="button" class="btn btn-default" data-dismiss="modal">Cancel</button>
                <button id="deleteButton" type="button" class="btn btn-primary">Confirm</button>
            </div>
        </div>
    </div>
</div>

定义deleteButton的事件点击以发出ajax请求并将其删除。

 $("#deleteButton").on("click", function(e) {
    $.ajax({
        url: "@Url.Action("Delete", "Controller")",
        method: "POST",
        data: { id: @Model.Id }
    })
    .done(function(data) {
        // hide the modal
        $("#deleteConfirm").modal("hide");
        if (data.success) {
            // ok
        } else {
            // show errors
        }
    });
});

最后,在按钮上显示模式以确认删除。样本:

<a href="@(Url.Action<UnitsController>(c => c.Delete(Model.Entity.Id)))" 
   class="btn btn-primary col-md-offset-9 col-md-3" 
   id="deleteConfirmButton">Delete</a>

并设置事件。

$("#deleteConfirmButton").on("click", function() {
   $("#deleteConfirm").modal("show"); 
});

答案 1 :(得分:1)

您可以在按钮中添加OnClick:

with open('test.csv','w') as fp:
    a = csv.writer(fp, delimiter=',')
    for f in Fruit:
        explanation = f.findtext("Explanation")
        types = f.findall("Type")
        for t in types:
            a.writerow([t.text.encode('utf8'), explanation.encode('utf8')])