Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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

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);
        }
    }
like image 523
Dinesh Avatar asked Jun 03 '14 06:06

Dinesh


2 Answers

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;
}
like image 80
Ehsan Sajjad Avatar answered Oct 24 '22 15:10

Ehsan Sajjad


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);
}
like image 42
Andrei V Avatar answered Oct 24 '22 15:10

Andrei V