Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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

Tags:

c#

asp.net-mvc

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?

like image 824
Egor Avatar asked Nov 28 '16 18:11

Egor


1 Answers

You can response JavaScript which basically returns JavaScriptResult.

[HttpPost]
public ActionResult AddToWishList(int id, bool check)
{
    return JavaScript("window.location='/Account/Login'");
}
like image 134
Win Avatar answered Oct 21 '22 21:10

Win