【问题标题】:How to call MVC Controller function with javascript如何使用 javascript 调用 MVC 控制器函数
【发布时间】:2020-07-16 15:31:23
【问题描述】:

我的控制器中有这个功能:

        [HttpPost]
    public IActionResult DeleteBooking(string bookingId)
    {
        Console.WriteLine("id: " + bookingId);
        DeleteResult<IBooking> deleteResult = bookingDomain.DeleteBooking(Guid.Parse(bookingId));

        return View("Index");
    }

在我看来,我需要使用按钮删除预订。所以我做了一个javascript onclick函数。它转到我的控制器中的函数,但它传递 null 作为参数而不是 id 作为字符串 idk 再做什么......

function deleteBooking(bookingId) {

    console.log(bookingId);   // this works

    Swal.fire({
        title: 'Are you sure?',
        text: "You won't be able to revert this!",
        icon: 'warning',
        showCancelButton: true,
        confirmButtonColor: '#3085d6',
        cancelButtonColor: '#d33',
        confirmButtonText: 'Yes, delete it!'
    }).then((result) => {
        if (result.value) {
            $.ajax({
                type: 'POST',
                url: '/Booking/DeleteBooking/',   // the URL of the controller action method
                data: bookingId, // optional data
                success: function (result) {
                    Swal.fire(
                        'Deleted!',
                        'Your file has been deleted.',
                        'success'
                    )
                },
                error: function (req, status, error) {
                    Swal.fire(
                        'Error!',
                        'Your file could NOT be deleted.',
                        'error'
                    )
                }
            });
        }
    })
}

console.log(bookingID) 向我显示了正确的 id,但在控制器函数中我得到了 null。

【问题讨论】:

  • data: {"bookingId": bookingId),

标签: javascript asp.net-mvc model-view-controller


【解决方案1】:

尝试将 ajax 调用的数据部分更新为如下所示:

            $.ajax({
                type: 'POST',
                url: '/Booking/DeleteBooking/',   // the URL of the controller action method
                data: { bookingId:  bookingId } , // optional data
                success: function (result) {
                    Swal.fire(
                        'Deleted!',
                        'Your file has been deleted.',
                        'success'
                    )
                },
                error: function (req, status, error) {
                    Swal.fire(
                        'Error!',
                        'Your file could NOT be deleted.',
                        'error'
                    )
                }
            });

【讨论】:

    【解决方案2】:

    通过Ajax向控制器传递数据时,数据必须以键值对的形式发送,如下所示:

    data: { "bookingId":  bookingId }
    

    key必须与控制器中的参数名称相同。

    【讨论】:

      猜你喜欢
      • 2012-04-12
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2019-10-25
      • 2013-12-15
      • 2017-08-22
      • 2017-07-25
      • 1970-01-01
      相关资源
      最近更新 更多