如何从ASP.NET MVC中的JSONResult方法重定向到控制器操作?

ACP*_*ACP 25 asp.net-mvc redirecttoaction jsonresult

我基于他UserId作为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");
   }
}
Run Code Online (Sandbox Code Playgroud)

如何从asp.net mvc中的JsonResult方法重定向到控制器操作?任何建议......

编辑: 这似乎不起作用......

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 });
            }
Run Code Online (Sandbox Code Playgroud)

Dar*_*rov 56

这取决于您如何调用此控制器操作.当你使用JSON时,我想你是在AJAX中调用它.如果是这种情况,则无法从控制器操作重定向.您需要success在AJAX脚本的回调中执行此操作.实现目标的一种方法如下:

return Json(new 
{ 
    redirectUrl = Url.Action("Index", "Home"), 
    isRedirect = true 
});
Run Code Online (Sandbox Code Playgroud)

并在成功回调:

success: function(json) {
    if (json.isRedirect) {
        window.location.href = json.redirectUrl;
    }
}
Run Code Online (Sandbox Code Playgroud)

备注:确保包含isRedirect = false在JSON中,以防您不想重定向,这是控制器操作中的第一种情况.