Search code examples
asp.net-mvccontrollers

Call ActionA from ActionB then proceed with ActionB


I think I misunderstand something about MVC. I'm trying to do the following:

public class ControllerA : Controller
{
    public ActionResult Index()
    {
        // do code

        // perform action on ControllerB - something like:
        // RedirectToAction("Action", "ControllerB");

        // CARRY ON with more code
    }
}

public class ControllerB : Controller
{
    public void Action()
    {
        // do code
    }
}

Obviously RedirectToAction("Action", "ControllerB"); isn't working. So how do I do it? I guess I could have all controllers that need to use Action() inherit from ControllerB but that feels a really bad way to do it. Please help!


Solution

  • You have to return the ActionResult from RedirectToAction()

    return RedirectToAction("Action", "ControllerB");
    

    is what you need to do if you want RedirectToAction to actually redirect to an action. After you clarified what "isn't working" means to you I think you should just have all controllers inherit from a base. That is a pretty standard approach.

    public class ControllerA : ControllerB
    {
        public ActionResult Index()
        {
            // do code
    
            Action();
    
            // CARRY ON with more code
        }
    }
    
    public class ControllerB : Controller
    {
        public void Action()
        {
            // do code
        }
    }