【发布时间】:2017-04-12 13:51:14
【问题描述】:
我正在尝试使用 RedirectToAction() 从另一个控制器调用方法。但它不起作用。你能解释一下,我做错了什么吗?
[HttpPost]
public ActionResult AddToWishList(int id, bool check)
{
var currentUser = WebSecurity.CurrentUserId;
if (currentUser != -1)
{
// ...
}
else
{
return RedirectToAction("Login", "Account");
}
}
我在 HTML 中调用方法:
<script>
$(document).ready(function () {
/* call the method in case the user selects a checkbox */
$("#checkbox".concat(@Model.Id)).change(function () {
$.ajax({
url: '@Url.Action("AddToWishList", "Item")',
type: 'POST',
data: {
id: '@Model.Id',
check: this.checked
}
});
});
});
如果我使用它会起作用:
success: function (result) {
window.location.href = "@Url.Content("~/Account/Login")";
}
但我不需要在每次点击后导航到 Login(),只有当用户没有被授权时。你能解释一下我如何在控制器中使用重定向吗?
【问题讨论】:
-
Ajax 帖子是异步的,必须使用 JavaScript 重定向。您不能通过 ajax 发出 post 请求并让服务器端点将浏览器导航到新窗口。
-
为什么不在运行 $("#checkbox") 之前尝试将 if @model.id != -1...
标签: c# asp.net-mvc