user2585299
user2585299

Reputation: 883

RedirectToAction not working along with call to same controller's action through $.ajax

I am calling a controller's action method called RedirectToHome through an ajax call. Inside that action method I am using RedirectToAction to excute the Index method of Spa controller. This redirect is not working even though the code gets successfully executed. I assume this is happening because RedirectToHome is called through ajax call. That's why I also tried calling the Index method too using ajax call when the ajax call for first request is successful. But even through second ajax call, I see that Index method does gets called but the view is never rendered. There are no errors in the console.

$.ajax({
            url: '@HttpContext.Current.Request.Url' + "Account/RedirectToHome",
            data: { email: userEmail },
            success: function (data) {
                    $.ajax({
                    url: '@HttpContext.Current.Request.Url' + "Spa/Index",
                    data: { isAuthenticated:true,email: userEmail },
                        success: function () {
                    }
                    });
            }
    });

 public ActionResult RedirectToHome(string email)
    {
        if (ValidateDomain(email))
            return RedirectToAction("Index", "Spa", new { isAuthenticated = true, email = email });
        else
            return RedirectToAction("ExternalLoginFailure");

    }

Upvotes: 0

Views: 445

Answers (1)

Jeyhun Rahimov
Jeyhun Rahimov

Reputation: 3787

Use @Url.Action(), not Spa/Index.

$.ajax({
            data: { email: userEmail },
            success: function (data) {
                    $.ajax({
                    url: '@Url.Action("Index", "Spa")',
                    data: { isAuthenticated:true,email: userEmail },
                        success: function () {

                      //use your redirect code here, not in action
                      if(result.isValidDomain)
                      {
                        document.location.href = '@Url.Action("Index", "Spa")/' + '?isAuthenticated=' + true;
                      }
                      else
                      {
                        document.location.href = '@Url.Action("ExternalLoginFailure", "Controller")';
                      }

                    }
                    });
            }
    });

Upvotes: 1

Related Questions