How to redirect to a controller action from a JSONResult method in ASP.NET MVC?

ACP picture ACP · May 19, 2010 · Viewed 55.1k times · Source

I am fetching records for a user based on his UserId as a JsonResult...

public JsonResult GetClients(int currentPage, int pageSize)
{
   if (Session["UserId"] != "")
   {
      var clients = clirep.FindAllClients().AsQueryable();
      var count = clients.Count();
      var results = new PagedList<ClientBO>(clients, currentPage - 1, pageSize);
      var genericResult = new { Count = count, Results = results };
      return Json(genericResult);
   }
   else
   {
         //return RedirectToAction("Index","Home");
   }
}

How to redirect to a controller action from a JsonResult method in asp.net mvc?Any suggestion...

EDIT: This doesn't seem to work...

if (Session["UserId"] != "")
            {
                var clients = clirep.FindAllClients().AsQueryable();
                var count = clients.Count();
                var results = new PagedList<ClientBO>(clients, currentPage - 1, pageSize);
                var genericResult = new { Count = count, Results = results ,isRedirect=false};
                return Json(genericResult);
            }
            else
            {
                return Json({redirectUrl = Url.Action("Index", "Home"), isRedirect = true });
            }

Answer

Darin Dimitrov picture Darin Dimitrov · May 19, 2010

This will depend on how you are invoking this controller action. As you are using JSON I suppose that you are calling it in AJAX. If this is the case you cannot redirect from the controller action. You will need to do this in the success callback of the AJAX script. One way to achieve it is the following:

return Json(new 
{ 
    redirectUrl = Url.Action("Index", "Home"), 
    isRedirect = true 
});

And in the success callback:

success: function(json) {
    if (json.isRedirect) {
        window.location.href = json.redirectUrl;
    }
}

Remark: Make sure to include isRedirect = false in the JSON in case you don't want to redirect which is the first case in your controller action.