【问题标题】:How to return a JsonResult or an ActionResult in the same method depending on input?如何根据输入以相同的方法返回 JsonResult 或 ActionResult?
【发布时间】:2016-03-15 16:54:42
【问题描述】:

我遇到需要返回 JSONResult 或重定向的情况。 有可能吗?

例子:

public ActionResult Example(string code)
{
  if(string.IsNullorEmpty(code))
    return RedirectToAction("Index", "Home");
  else
    return Json(new { success = true, message= "Next step"});
}

【问题讨论】:

  • 是的,两者都可以返回,因为它们是ActionResults。但是,如果您在 Ajax 调用中返回 RedirectToAction,它将不会重定向。这是你的问题吗?

标签: c# asp.net-mvc redirect model-view-controller jsonresult


【解决方案1】:

是的,这是可能的。其实你贴的代码就是你的做法!

Controller.RedirectToAction 返回 RedirectToRouteResultController.Json 返回 JsonResult。它们都继承自ActionResult,因此将它们作为ActionResult 返回就可以了。


如果您使用 AJAX:

即使您没有说明调用上下文是什么,正如 insightful comment by Thiago Ferreira 所提到的,重定向也不适用于 AJAX。 你需要返回一个错误信息,然后在客户端进行处理。

例如关于你的操作方法:

public ActionResult Example(string code)
{
    if(string.IsNullorEmpty(code))
    {
        UrlHelper urlHelper = new UrlHelper(HttpContext.Request.RequestContext);
        string actionUrl = urlHelper.Action("Index", "Home");
        return Json(new { success = false, message = "Code not provided", redirectTo = actionUrl});
    }
    else
    {
        return Json(new { success = true, message= "Next step"});
    }
}

在客户端处理它:

if(response.success) {
    // yay
} else if(response.redirectTo) {
    window.location.href = response.redirectTo;
}

【讨论】:

  • 这种方法可能是首选,但您可以返回 JsonResult 或 RedirectToAction。尽管您必须让 Ajax 调用的成功/失败/完成功能能够检查响应是返回视图还是 json 对象。否则回调将不知道是否渲染内容,将其插入到哪个 DOM 元素下,或者他们是否应该基于 Json 执行一些逻辑。
  • 但是在什么情况下我们可以在单一方法中同时使用这两种方法呢?事实上是这样吗?
猜你喜欢
  • 1970-01-01
  • 1970-01-01
  • 2019-10-26
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 2018-11-13
  • 1970-01-01
  • 2022-01-13
相关资源
最近更新 更多