Problems with RedirectToAction MVC2 - Cannot implicitly convert type 'System.Web.Mvc.RedirectToRouteResult' to 'System.Web.Mvc.ViewResult'

liam picture liam · Jun 3, 2011 · Viewed 11.2k times · Source

I am receiving this error when trying to use RedirectToAction, can anyone offer any advice on why this could be occuring, ive used this before without any problems, i must be missing something.

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

 [HttpPost]
    public ViewResult Edit(Customer customer)
    {
        if (ModelState.IsValid)
        {
            customersRepository.SaveCustomer(customer);
            TempData["message"] = customer.CustomerName + " has been saved.";
            return RedirectToAction("Index");
        }

        else //validation error, so redisplay the same view
            return View(customer);

    }

Regards

Liam

Answer

jao picture jao · Jun 3, 2011

Try changing public ViewResult Edit(Customer customer) to public ActionResult Edit(Customer customer)

ViewResult is derived from ActionResult and can only return Views. Since your code can return a View or a Redirect, you should use an ActionResult. See this answer for more information.