Egor Egor - 8 days ago 5
C# Question

Redirect to new page from Server for ASP.Net MVC Ajax Request

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");
}
}


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")";
}


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?

Win Win
Answer

You can response JavaScript which basically returns JavaScriptResult.

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