ViVi ViVi - 11 days ago 4
C# Question

Redirect to action with JsonResult

I have a view. When user clicks on a button in my view, I am trying to get some data from my view without reloading my view through an AJAX POST to display some data.

This is the method in my controller :

[HttpPost]
public JsonResult GetUserTraj()
{
var userTrajList =
DBManager.Instance.GetUserTraj(Session["UserName"].ToString());
return Json(userTrajList);
}


This returns a Json Result. I am trying to implement session now. So if the session has expired, I want user to be redirected to the Login view. In the above case if the session expires
Session["UserName"]
becomes null and an exception is raised.

[HttpPost]
public JsonResult GetUserTraj()
{
if (Session["UserName"] != null)
{
var userTrajList =
DBManager.Instance.GetUserTraj(Session["UserName"].ToString());
return Json(userTrajList);
}
else
{
RedirectToAction("Login", "Login");
return Json(null);
}
}


I tried the above code. But it doesn't work. It does not redirect the user to the Login view. I tried
return RedirectToAction("Login", "Login");
. But that doesn't work since the controller action method cannot return something other than
JsonResult
. Please help me find a solution for the same.

Answer

If you use AJAX to request a page, it's cant redirect in browser. You should response a status code, and then use javascript to redirect in front, like this

   [HttpPost]
public JsonResult GetUserTraj()
{
    if (Session["UserName"] != null)
    {
        var userTrajList =
            DBManager.Instance.GetUserTraj(Session["UserName"].ToString());
        return Json(userTrajList);
    }
    else
    {
        //RedirectToAction("Login", "Login");
        return Json(new {code=1});
    }
}

You need write this condition Inside of your Ajax success call to reload login screen,

     if(result.code ===1){
      window.location = 'yourloginpage.html'
     }
Comments