【发布时间】:2017-11-21 19:37:34
【问题描述】:
我在 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
}
我总是得到参数值为空,我不知道为什么。我尝试用几种不同的方式调用这个带有参数的动作,就像我在这个论坛上看到的一样,但没有成功。
【问题讨论】:
-
“我的参数总是为空”在哪里?以及哪些参数?
-
在控制器中用于参数 customerComment 和 customerDate。在 javascript 函数中是正确的,我生成 ComfirmOrder.successUrl,例如:http://localhost:1234/checkout/completed/?customerComment='test'&customerDate='2017-12-25'。我也试过 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" })';但不能正常工作。
-
如果你在控制器中放了一个断点,它会打到它吗?
-
检查你的 AJAX,你也在执行一个 'POST' 方法,在你的控制器的方法上面写 [HttpPost]。
-
AJAX 部分没问题,我得到了我需要的所有数据。有问题的是在 if(response.success) 中调用 Controller Action。这两个尝试不会给 Action 方法带来参数。我来到 Controller Action 方法,但参数 customerComment 和 customerData 为空。目前我有 ConfirmOrder.successUrl = 'localhost:12345/checkout/completed/test/2017-12-25 不起作用,请致电 window.location.href = '@Html.GetUrl("Completed", "Checkout", new { customerComment = "test", customerDate = "2018-12 -31" })';我应该如何正确调用我的控制器操作?
标签: javascript c# asp.net-mvc