【问题标题】:Error in sending parameters to controller through @Url.Action in JQuery通过 JQuery 中的 @Url.Action 向控制器发送参数时出错
【发布时间】:2016-05-24 09:21:37
【问题描述】:

我正在处理一个MVC 项目,并尝试使用@Url.Action 将一些参数发送到JQuery 中的控制器。

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>
 }

【问题讨论】:

  • 您正在将事件处理程序与demo3类绑定
  • 对不起,我在复制代码时犯了一个错误。事实上,我正在使用类 demo1 构建一个事件处理程序。我会更新问题

标签: jquery asp.net-mvc url-action


【解决方案1】:

使用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();
    });
});

【讨论】:

  • var id = $(this).data('id'); 为我工作,但 id 作为 null 返回给控制器。请注意,html 按钮放置在 foreach 循环中。检查更新的问题。
【解决方案2】:

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

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 页面错误,你也会有足够的信息。

希望这会有所帮助!!!

【讨论】:

    猜你喜欢
    • 2016-03-02
    • 1970-01-01
    • 2014-10-31
    • 2011-07-03
    • 2014-04-26
    • 1970-01-01
    • 2021-04-23
    • 1970-01-01
    相关资源
    最近更新 更多