【问题标题】:Redirect to new page from Server for ASP.Net MVC Ajax Request从 ASP.Net MVC Ajax 请求的服务器重定向到新页面
【发布时间】: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


【解决方案1】:

您可以回复 JavaScript,基本上返回 JavaScriptResult

[HttpPost]
public ActionResult AddToWishList(int id, bool check)
{
    return JavaScript("window.location='/Account/Login'");
}

【讨论】:

  • @KarlGjertsen 有什么问题?此答案在 MVC 中返回 ActionResult
  • @KarlGjertsen 没问题。我更新了答案以使其清楚。
【解决方案2】:

补充@Win 的答案 - 我有一个用例,在我的 ASP.NET MVC 应用程序中有一个旧的 ASPX 文件。而且,我必须从返回 ActionResult 的 MVC 操作导航到该 ASPX 页面。所以,我做了这样的事情来从我的操作导航到那个 ASPX 页面。我必须为导航创建一个绝对 URL。

var myLegacyPageUrl = Request.Url.Scheme 
                                   + "://"
                                   + Request.Url.Authority
                                   + Url.RequestContext.HttpContext.Request.ApplicationPath
                                   + "/mylegacypage.aspx?";
                return JavaScript(string.Format("window.location='{0}'", errorPageUrl));

希望有人发现它在现代 MVC 网站中存在遗留网页的情况下有用。

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 2013-11-22
    • 1970-01-01
    • 2018-07-10
    • 1970-01-01
    • 1970-01-01
    • 2015-12-13
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多