带有javascript函数参数的MVC ActionLink [关闭]

问题描述 投票:-2回答:2

我在下拉菜单中有一个按钮,如下所示:

<li><button class="btn btn-white btn-sm delete-group fa fa-trash" dataid="@item.InterimReviewId">Delete</button></li>

调用这样的javascript函数:

        $('.delete-group').click(function () {
            var url = "/Fiscalizations/Delete";
            var id = $(this).attr('dataid');
            $.get(url + '/' + id, function (data) {
                $('#editor-content-container').html(data);
                $('#editor-container').modal('show');
            });
        });

调用模态窗口:

<div class="modal fade" id="editor-container" tabindex="-1"
     role="dialog" aria-labelledby="editor-title">
    <div class="modal-dialog modal-md" role="document">
        <div class="modal-content animated flipInY" id="editor-content-container"></div>
    </div>
</div>

一切都按我的预期进行。我的目标是用ActionLink交换按钮,这里我的问题就开始了。

我写了这样的东西:

<li>@Html.ActionLink("Delete Interim Review", "Delete", "InterimReviews", new { dataid = item.InterimReviewId }, new { @class = "delete-group" })</li>

它正确调用函数但不是模态窗口,而是使用地址/InterimReviews/Delete?dataid=1调用错误的HTTP请求

我会很感激任何提示如何解决问题

编辑:我解决了错误请求的问题(控制器和Action Link中的不同参数名称)。所以现在唯一的问题是,使用ActionLink javascript函数不会触发模态窗口

javascript jquery asp.net asp.net-mvc actionlink
2个回答
0
投票

单击锚标记通常会对URL进行正常的GET请求。所以你需要防止这种默认行为。您可以使用jquery preventDefault方法来执行此操作。另一种选择是在方法结束时使用return false

假设,Delete动作方法有一个名为dataid的参数,你可以使用Html.ActionLink方法,它将使用正确的路径值(querystring)为动作方法生成正确的相对URL(例如:\InterimReviews\Delete?dataid=101)。如果您的参数名称不同,请更新您的剃刀代码以使用它(您正在使用的重载中的第四个参数)所以您所要做的就是,阅读点击的锚标记的URL并将其用于您的呼叫。无需自己进行任何字符串连接以将id添加到url!

$(function () {

    $('a.delete-group').click(function (e) {
        e.preventDefault();

        var url = $(this).attr("href");
        $.get(url, function (data) {
            $('#editor-content-container').html(data);
            $('#editor-container').modal('show');
        });
    });

});

我还强烈建议您将删除操作更改为HttpPost类型操作。任何更新/删除数据的操作方法都应该是POST类型。如果您正在显示确认对话框,GET就可以了。但是对于实际的删除,使用HttpPost类型的动作方法并使用来自客户端的$.post调用。


0
投票

当您使用ActionLink时,您将创建此:

<a href="Delete/InterimReviews" class="delete-group" data-id="">Delete Interim Review</a>

因此,当您单击该链接时,浏览器将导航到Delete/InterimReviews。您需要做的是阻止浏览器将<a>视为链接(preventDefault()),您可以这样做:

$('.delete-group').click(function (e) {
        e.preventDefault(); //this will stop the link 
        var url = "/Fiscalizations/Delete";
        var id = $(this).attr('dataid');
        $.get(url + '/' + id, function (data) {
            $('#editor-content-container').html(data);
            $('#editor-container').modal('show');
        });
    });

另外,使用dataid作为html属性无效 - 你应该使用像data-id这样的东西,可以使用剃刀中的data_id创建,并且可以使用$.data('id')读取。

© www.soinside.com 2019 - 2024. All rights reserved.