ASP.NET MVC使用javascript函数中的参数调用Controller Action

时间:2017-11-21 19:37:34

标签: javascript c# asp.net-mvc

我在ASP.NET MVC C#中有Web应用程序。我想用来自javascript的参数调用Controller Action方法,但我总是为参数提供null。

在.js我有:

$.ajax({
    cache: false,
    url: this.saveUrl,
    type: 'post',
    success: this.nextStep,
    complete: this.resetLoadWaiting,
    error: Checkout.ajaxFailure
});

nextStep: function (response) {
    if (response.error) {
        if ((typeof response.message) == 'string') {
            alert(response.message);
        } else {
            alert(response.message.join("\n"));
        }

        return false;
    }

    if (response.redirect) {
        ConfirmOrder.isSuccess = true;
        location.href = response.redirect;
        return;
    }
    if (response.success) {
        ConfirmOrder.isSuccess = true;
        window.location = ConfirmOrder.successUrl;
        //window.location.href = @Url.Action("Completed", "Checkout", new { customerComment = "test", customerDate = "2018-12-31" });
        //window.location.href = '@Html.GetUrl("Completed", "Checkout", new { customerComment = "test", customerDate = "2018-12-31" })';
    }

    Checkout.setStepResponse(response);
}
在RouteProvider.cs中

我有:

        routes.MapLocalizedRoute("CheckoutCompleted",
                        "checkout/completed/{orderId}/{customerComment}/{customerDate}",
                        new { controller = "Checkout", action = "Completed", orderId = UrlParameter.Optional, customerComment = UrlParameter.Optional, customerDate = UrlParameter.Optional },
                        new { orderId = @"\d+", customerComment = @"\w+", customerDate = @"\w+" },
                        new[] { "Nop.Web.Controllers" });

最后在控制器中我有:

    public virtual ActionResult Completed(int? orderId, string customerComment, string customerDate)
    {
        //some code here
    }

我总是得到参数值null,我不知道为什么。我尝试用几种不同的方式调用这个Action,就像我在这个论坛上看到的但没有成功。

2 个答案:

答案 0 :(得分:0)

您是否在控制器中添加了httpPost包装器?

g++
在你的Ajax代码中你没有提到你的数据类型和数据试试这个Ajax

[HttpPost]
     public virtual ActionResult Completed(MyClass  MyClassObj )
     {
            //some code here
     }

答案 1 :(得分:0)

错误在于url字符串。正确的是

ConfirmOrder.successUrl =“http://localhost:8079/checkout/completed/?customerComment=eee&customerEstimateShippingDate=2017-11-14

我在这个答案中找到了这个解决方案:Routing with Multiple Parameters using ASP.NET MVC

我不需要使用新参数更新RouteProvider。在Controller Action方法中输入就足够了。其他事情会自动发生。