Cannot implicitly convert type 'System.Web.Mvc.RedirectToRouteResult' to 'System.Web.Mvc.JsonResult'

随声附和 提交于 2019-12-10 15:16:55

问题


How can i Redirect To Action from JsonResult to ActionResult but i m getting error. my error is "Cannot implicitly convert type 'System.Web.Mvc.RedirectToRouteResult' to 'System.Web.Mvc.JsonResult'". My Code

Json Result:

   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);
   }

ActionResult:

    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);
        }
    }

回答1:


You need to use base class ActionResult so that you can return View,JSON,Content or Partial View:

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);
   }

But if you are calling this action via ajax you have to redirect to that action via javascript because returning RedirectToAction will return the html in response of ajax but not a redirect.

So you need to return action url via json with some flag and check that if response has that flag, redirect to that url via jquery.

In Ajax call success check if its url:

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



回答2:


The JsonResult class implements the ActionResult class. Just change the JsonResult to ActionResult as return type for your action method:

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);
}


来源:https://stackoverflow.com/questions/24008137/cannot-implicitly-convert-type-system-web-mvc-redirecttorouteresult-to-system

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!