开发者

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()
    {
        /开发者_StackOverflow中文版/ 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!


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


I believe the controller you are currently executing is an instance of the class so you would need to make an instance of controller B to be able to execute anything on it, so what you are trying to do there just won't really work without a hack.

I think however there is 2 methods to better get the results i think you are after:

1) Make a 'ControllerBase' class and have all controllers inherit from it instead of from 'Controller' then any shared code you can add into the base class (as a static method perhaps) and then all controllers can access it as a member nice and easy.

2) As MVC will make a straight up DLL you can add in new classes as you need, eg add a new project folder like 'Globals' add a new class file called 'Funcs' and there you have a static lib that you can access from anywhere, Funcs.SendEmail(); etc

If i'm off the mark ok! happy coding anyway heh


I have injected controllers with a factory method from the controller factory as a delegate (Func CreateController), and used that to create sub-controllers, such as in this circumstance. There's plenty of ways to accomplish your goal, but I think that might be quick way to get what you want working.

0

上一篇:

下一篇:

精彩评论

暂无评论...
验证码 换一张
取 消

最新问答

问答排行榜