使用JsonResult重定向到操作 [英] Redirect to action with JsonResult
问题描述
我有一个看法.当用户单击视图中的按钮时,我试图从视图中获取一些数据,而没有通过AJAX POST重新加载视图以显示一些数据.
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);
}
这将返回Json结果.我正在尝试实施会议.因此,如果会话已过期,我希望将用户重定向到登录"视图.在上述情况下,如果会话到期,Session["UserName"]
变为null并引发异常.
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);
}
}
我尝试了上面的代码.但这是行不通的.它不会将用户重定向到登录"视图.我尝试了return RedirectToAction("Login", "Login");
.但这不起作用,因为控制器操作方法不能返回JsonResult
以外的其他值.请帮助我找到相同的解决方案.
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.
推荐答案
如果使用AJAX请求页面,则无法在浏览器中重定向. 您应该回复一个状态码,然后使用javascript像这样
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});
}
}
您需要编写此条件,然后在Ajax成功调用中重新加载登录屏幕,
You need write this condition Inside of your Ajax success call to reload login screen,
if(result.code ===1){
window.location = 'yourloginpage.html'
}
这篇关于使用JsonResult重定向到操作的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!