在JQuery中通过@Url.Action向控制器发送参数时出错

Error in sending parameters to controller through @Url.Action in JQuery

我正在做一个 MVC 项目,我试图在 JQuery 中使用 @Url.Action 向我的控制器发送一些参数。

HTML代码:

<button class="btn btn-white btn-sm demo1" data-id='@item.TeamID'>Delete</button>

JQuery代码:

    $(document).ready(function () {
        $('.demo1').click(function (event) {
            swal({
                title: "Are you sure?",
                text: "You will not be able to recover this team!",
                type: "warning",
                showCancelButton: true,
                confirmButtonColor: "#DD6B55",
                confirmButtonText: "Yes, delete it!",
                closeOnConfirm: false
            }, function () {
                var data = event.data;
                var id = data.id;
                var url = '@Url.Action("Delete", "Teams", new { id = "__param__" })';
                window.location.href = url.replace('__param__', encodeURIComponent(id));

                swal("Deleted!", "Your team has been deleted.", "success");
            });
        });
    });

但是,未触发 Teams 控制器中的 Delete 方法。我错过了什么吗?

更新: HTML 按钮放置在 foreach 循环中:

@foreach (var item in Model)
{
    <tr>
          <td>
              @Html.DisplayFor(modelItem => item.TeamName)
          </td>
          <td>
              @Html.DisplayFor(modelItem => item.TeamInits)
          </td>
          <td>
              @Html.ActionLink("Edit", "Edit", new { id = item.TeamID }, new { @class = "btn btn-white btn-sm" })
              <button class="btn btn-white btn-sm demo1" data-id='@item.TeamID'>Delete</button>
          </td>
      </tr>
 }

使用HTMLElement.dataset属性或.data()读取自定义data-*前缀属性值。

$(document).ready(function () {
    $('.demo1').click(function (event) {            
        var id = this.dataset.id; 
        //OR
        var id = $(this).data('id');

        //Rest of the code
        swal();
    });
});

我通常尝试下面的代码技巧。当出现这样的问题时。

在你的 Global.asax.cs 文件中添加下面的代码并将调试器放入方法中,以便在发生异常时触发它。

protected void Application_Error(object sender, EventArgs e)
{ 
    Exception exception = Server.GetLastError();
    string ex = exception.Message; // Here you will get to know what is going wrong
}

异常消息或堆栈跟踪将提供足够的信息详细信息来修复错误。

即使它来自 Jquery / Razor Html 页面的请求错误,您也会有足够的信息。

希望对您有所帮助!!!