【问题标题】:Cannot implicitly convert type 'System.Web.Mvc.RedirectToRouteResult' to 'System.Web.Mvc.JsonResult'无法将类型“System.Web.Mvc.RedirectToRouteResult”隐式转换为“System.Web.Mvc.JsonResult”
【发布时间】:2014-07-23 08:58:27
【问题描述】:

如何从 JsonResult 重定向到 ActionResult 到 ActionResult 但我收到错误。我的错误是“无法将类型'System.Web.Mvc.RedirectToRouteResult'隐式转换为'System.Web.Mvc.JsonResult'”。 我的代码

Json 结果:

   public JsonResult AddTruckExpensesTransactionChild(string totaldays, string amount)
   {
        string Mess = objActive.Save();
        if (Mess == "1")
        {
            return RedirectToAction("GetTruckExpensesChild", new { id="", sid="" });
        }
        return Json(Mess, JsonRequestBehavior.AllowGet);
   }

动作结果:

    public ActionResult GetTruckExpensesChild(string id, string sid)
    {
        TruckExpensesTransactionClass Transaction = new TruckExpensesTransactionClass();
        if (sid != null)
        {                
            Transaction.TransactionChild = objActive.ShowTransactionChild(id, sid);
            return View(Transaction);
        }
        else
        {                
            return View(Transaction);
        }
    }

【问题讨论】:

    标签: c# asp.net-mvc json model-view-controller asp.net-mvc-2


    【解决方案1】:

    您需要使用基类 ActionResult 以便可以返回 ViewJSONContent 或 局部视图:

    public ActionResult AddTruckExpensesTransactionChild(string totaldays, string amount)
       {
            string Mess = objActive.Save();
            if (Mess == "1")
                  return Json(new { Url = Url.Action("GetTruckExpensesChild", new { id = "", sid = "" }) });
    
            return Json(Mess, JsonRequestBehavior.AllowGet);
       }
    

    但是,如果您通过 ajax 调用此操作,则必须通过 javascript 重定向到该操作,因为返回 RedirectToAction 将返回 html 以响应 ajax 而不是重定向。

    因此,您需要通过带有一些标志的 json 返回操作 url,并检查是否响应具有该标志,通过 jquery 重定向到该 url。

    在 Ajax 调用成功检查它的 url:

    success: function(result) {
              if(result.Url.length > 0)
    {
            window.location.href=result.Url;
    }
    

    【讨论】:

    • 是的,此代码返回到该操作,但我的页面未重定向。
    • 你必须返回你想要通过jquery重定向和重定向的url
    • 我无法理解,请给我示例代码,因为我是 jquery 新手
    • 没有朋友不工作
    • 输入alert(result)查看返回的内容
    【解决方案2】:

    JsonResult 类实现了ActionResult 类。只需将 JsonResult 更改为 ActionResult 作为您的操作方法的返回类型:

    public ActionResult AddTruckExpensesTransactionChild(string totaldays, string amount)
    {
        string Mess = objActive.Save();
        if (Mess == "1")
        {
            return RedirectToAction("GetTruckExpensesChild", new { id="", sid="" });
        }
        return Json(Mess, JsonRequestBehavior.AllowGet);
    }
    

    【讨论】:

    • 是的,此代码返回到该操作,但我的页面未重定向。
    猜你喜欢
    • 2018-11-22
    • 2011-09-07
    • 1970-01-01
    • 2020-01-14
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2019-08-18
    • 2022-01-15
    相关资源
    最近更新 更多