mvc模态删除按钮不使用jquery

时间:2015-09-27 04:22:17

标签: jquery html5 razor model-view-controller

我有一个用于删除记录的partialView。我创建了一个按钮来处理删除,但我似乎无法通过按钮触发jquery。

如果我添加功能" deleteRecord"按钮jquery将触发

<button class="btn btn-primary" data-id=@ViewData["id"] id="btnContinueDelete" onclick="deleteRecord(); return false;">Delete Sales Order</button>

然而,当我使用“id&#39;要执行jquery按钮不会触发

<button class="btn btn-primary" data-id=@ViewData["id"] id="btnContinueDelete">Delete Sales Order</button>

用于执行partialView

<a class="btn deleteOrder btn-danger" data-modal="" href="@Url.Action("_DeleteConfirmation", "WebOrder", new { id = @Model.Web_Order_ID, shipToName=@Model.Ship_To_Name }) role="button" data-toggle="modal">
    <span class="glyphicon glyphicon-edit"></span>
</a>

这是PartialView

<!-- Modal -->
<div class="modal-header">
    <button type="button" class="close" data-dismiss="modal" aria-hidden="true">×</button>
    <h3>Ship_To_Name</h3>
</div>
<div class="modal-body">
    <p>
        Are you sure you want to delete this Sales Order <label id="shipto-name">@ViewData["name"]</label> ID:
        <label id="data-id">@ViewData["id"]</label>
    </p>
</div>
<div class="modal-footer">
    <button class="btn" data-dismiss="modal" aria-hidden="true">Cancel</button>
    <button class="btn btn-primary" data-id=@ViewData["id"] id="btnContinueDelete" onclick="writeRecord(); return false;">Delete Sales Order</button>

</div>

这里是jquery:

$(function () {
    $.ajaxSetup({ cache: false, async: true });

    $("a[data-modal]").on("click", function (e) {
        $('#myModalContent').load(this.href, function () {
            $('#myModal').modal({
                keyboard: true
            }, 'show');

            bindForm(this);
        });
        return false;
    });

    //Not working funtion
    $('#btnContinueDelete').click(function() {
        var id = $("button[data-id]").val();
        $.post(Url.Action("_DeleteConfirmation", "WebOrder"), { id: id }, function(data) {
            alert("data deleted");
        });
    });
});

// Working function
function writeRecord() {
    var id = $("button[data-id]").val();
    $.post(Url.Action("_DeleteConfirmation", "WebOrder"), { id: id }, function (data) {
        alert("data deleted");
    });
}

1 个答案:

答案 0 :(得分:0)

因为您的部分视图是动态加载的,所以当您注册时,click事件将无效,因为到那时该id不存在。

您需要使用on,例如:

$('#myModalContent').on('click', '#btnContinueDelete', function(event){
        var id = $("button[data-id]").val(); // remember change this
        $.post(Url.Action("_DeleteConfirmation", "WebOrder"), { id: id }, function(data) {
            alert("data deleted");
        })
});

有关on的更多信息,请查看jquery网站:http://api.jquery.com/on/