How can i Execute a Controller's ActionMethod programatically?
Posted
by Pure.Krome
on Stack Overflow
See other posts from Stack Overflow
or by Pure.Krome
Published on 2010-04-14T15:42:53Z
Indexed on
2010/04/14
16:03 UTC
Read the original article
Hit count: 435
Hi folks,
I'm trying to execute a controller's Action Method programatically and I'm not sure how.
Scenario: When my ControllerFactory fails to find the controller, I wish it to manually execute a single action method which i have on a simple, custom controller. I don't want to rely on using any route data to determine the controller/method .. because that route might not have been wired up.
Eg.
// NOTE: Error handling removed from this example.
public class MyControllerFactory : DefaultControllerFactory
{
protected override IController GetControllerInstance(Type controllerType)
{
IController result = null;
// Try and load the controller, based on the controllerType argument.
// ... snip
// Did we retrieve a controller?
if (controller == null)
{
result = new MyCustomController();
((MyCustomController)result).Execute404NotFound(); // <-- HERE!
}
return result;
}
}
.. and that method is ..
public static void Execute404NotFound(this Controller controller)
{
result = new 404NotFound();
// Setup any ViewData.Model stuff.
result.ExecuteResult(controller.ControllerContext); // <-- RUNTIME
// ERROR's HERE
}
Now, when I run the controller factory fails to find a controller, i then manually create my own basic controller. I then call the extension method 'Execute404NotFound' on this controller instance. That's fine .. until it runs the ExecuteResult(..) method. Why? the controller has no ControllerContext data. As such, the ExecuteResult crashes because it requires some ControllerContext.
So - can someone out there help me? see what I'm doing wrong.
Remember -> i'm trying to get my controller factory to manually / programmatically call a method on a controller which of course would return an ActionResult.
Please help!
© Stack Overflow or respective owner