从服务器重定向到ASP.Net MVC Ajax请求的新页面

问题描述:

我正在尝试使用RedirectToAction()从另一个控制器调用方法.但这是行不通的.您能解释一下,我在做什么错吗?

I'm trying to call a method from another controller using RedirectToAction(). But it doesn't work. Could you please explain, what I'm doing wrong?

[HttpPost]
public ActionResult AddToWishList(int id, bool check)
{
    var currentUser = WebSecurity.CurrentUserId;
    if (currentUser != -1)
    {
        // ...              
    }
    else
    {
        return RedirectToAction("Login", "Account");
    }            
}

我用HTML调用该方法:

I call the method in 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
            }
        });
    });
});

如果我使用,它会起作用:

It works if I use:

success: function (result) {
    window.location.href = "@Url.Content("~/Account/Login")";
}

但是,只有在未授权用户的情况下,我不需要在每次单击后导航到Login().您能解释一下如何在控制器中使用重定向吗?

But I don't need to navigate to the Login() after every click, only if the user is not authorized. Could you please explain how I can use redirect in the controller?

您可以回复 JavaScriptResult .

You can response JavaScript which basically returns JavaScriptResult.

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