Jquery UI, Razor and MVC: Uncaught TypeError: Illegal invocation

Jquery UI, Razor and MVC: Uncaught TypeError: Illegal invocation

正在尝试获取 Jquery UI 对话框以确认(确定,取消)对删除操作 (DeleteTestUser) 的调用。我的 jquery ui 对话框在点击时出现。取消按钮按预期工作,但确定不是。

错误(未捕获的类型错误:非法调用)是 Chrome 在我单击“确定”时在控制台中显示的内容。这可能并不奇怪,因为它不知道 testUser.TestUserId 是什么...

我如何最终将该值从客户端传递到服务器? HomeController.cs 中的删除操作在没有确认对话框的情况下也能正常工作。我需要确定才能调用它。我觉得我很接近但不确定如何在 Javascript.

中形成 Url.Action post

我很确定有问题的行是 _layout.cshtml

中的 post

_layout.cshtml

    <script type="text/javascript">
    $(document).ready(function() {

        $('#dialog-modal').dialog(
            {
                title: 'Test User',
                draggable: false,
                resizeable: false,
                closeOnEscape: true,
                modal: true,
                autoOpen: false,
                buttons: {
                    'Cancel': function() {
                        $(this).dialog('close');
                    },
                    'OK': function() {
                        $.post("@Url.Action("DeleteTestUser", "Home")",
                            { id: $('testUser.TestUserId') });
                        $(this).dialog('close');
                    }

                }
            });

        $('#confirm-delete').click(function () {
            $('#dialog-modal').dialog("open");
        });
    });
</script>

HomeController.cs

    public ActionResult DeleteTestUser(int id)
    {
        this.testUserBusinessLogic.DeleteTestUser(id);
        return this.RedirectToAction("Index");
    }

index.cshtml

    @foreach (var testUser in this.Model)
    {
        <tr>
            <td>@testUser.FirstName</td>
            <td>@testUser.LastName</td>
            <td>@testUser.EmailAddress</td>
            <td>
                <a href="@Url.Action("TestUser", "Home",
                        new {id = testUser.TestUserId})">
                    <i class="fa fa-pencil fa-lg text-primary"></i>
                </a>
            </td>
            <td>
                <a href="#" id="confirm-delete" >
                    <i class="fa fa-trash fa-lg text-primary"></i>
                </a>
            </td>
        </tr>
    }

更改生成 link 的代码以删除重复的 id 属性(改用 class 名称)并添加 data- 属性以存储 TestUserId

<td>
    <a href="#" class="confirm-delete" data-id="@testUser.TestUserId">
        <i class="fa fa-trash fa-lg text-primary"></i>
    </a>
</td>

在脚本中,您可以在调用 open

之前检索该值并将其分配给对话框的 data- 属性
$('.confirm-delete').click(function () { // modify selector
    var id = $(this).data('id');
    $('#dialog-modal').data('id', id).dialog("open");
});

并在单击“确定”按钮时检索它

$('#dialog-modal').dialog(
    ....
    buttons: {
        'Cancel': function() {
            $(this).dialog('close');
        },
        'OK': function() {
            $.post('@Url.Action("DeleteTestUser", "Home")', { id: $('#dialog-modal').data('id') });
            $(this).dialog('close');
        }
    }
});