Cannot implicitly convert type 'System.Web.Mvc

2019-06-22 06:52发布

问题:

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