【问题标题】:Pass in parameter from ajax success response to Url Action method将 ajax 成功响应中的参数传递给 Url Action 方法
【发布时间】:2019-05-21 22:23:16
【问题描述】:

我有一个对 Api 的 ajax 调用,它将数据添加到数据库中,我希望成功函数调用一个具有操作方法的控制器,以不同于从 API 调用的响应接收到的参数。我该怎么做呢

Ajax 调用

 $.ajax({
            //Url should contain the method you want to run
            url: "/api/ApiTest",
            //Method will be one of the REST API verb
            method: "POST",
            //These are all the parameters to be passed to method for rest api
            data:viewModel,
            dataType: 'json',
            success: function (data) {
                var bookingIDParam = data.Booking.BookingID
                window.location.href = '@Url.Action("BookingInfo", "Booking", new { BookingID = bookingIDParam })';
            },
            error: function () {
                alert("Error occured!!")
            }
        });

我收到错误消息“当前上下文中不存在名称‘bookingIDParam’

如何调用不同的控制器/转到带有响应参数的操作方法的 url。

【问题讨论】:

  • 你不能;至少不是你想要的。所有服务器端的事情都发生在最终页面交付给客户端之前。 AJAX 调用在此之后发生,AJAX 响应甚至在此之后发生。您将不得不使用 javascript 调整 URL。您可以在 razor 代码中执行类似 new { BookingID = "REPLACEME" } 的操作,然后当您获得 AJAX 响应时,将结果 URL 中的 REPLACEME 替换为 AJAX 响应中的值。如果令人困惑,请查看浏览器中的该行。你会看到window.location.href = 'some real URL';

标签: c# jquery ajax asp.net-mvc razor


【解决方案1】:

稍后尝试设置一些虚拟字符串来替换它:

var url_redirect = '@Url.Action("BookingInfo", "Booking", new { BookingID = "00replace00" })';

$.ajax({
    ....


      success: function (data) {
                url_redirect = url_redirect.replace("00replace00", data.Booking.BookingID );
                window.location.href =url_redirect ;
            },

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2015-08-01
    • 1970-01-01
    相关资源
    最近更新 更多