I have this MVC4 controller (ControllerB
):
public class MyControllerB : Controller
{
public bool Check(string actionName, ControllerBase con
The ControllerContext
is null because you are manually creating the ControllerB
instance from ControllerA
.
Normally, IController
instances are created by the registered IControllerFactory
, typically System.Web.Mvc.DefaultControllerFactory
. The controller factory will new()
the instance and initialize settings properly.
As @DZL says, it is normally much better to have both controllers subclass a BaseController
class, which can have shared initialization and shared properties and methods.
I don't understand the business logic of what you are trying to do, but here's a code example of using the base class from the 2 controllers:
namespace MyNamespace.Controllers
{
public class MyControllerBase : Controller
{
public bool Check(string actionName, ControllerBase controllerBase)
{
ControllerContext controllerContext = new ControllerContext(this.ControllerContext.RequestContext, controllerBase);
return false;
}
}
public class MyControllerA : MyControllerBase
{
ActionResult Index()
{
bool b = base.Check("Index", this);
return View();
}
}
public class MyControllerB : MyControllerBase
{
ActionResult Index()
{
bool b = base.Check("Index", this);
return View();
}
}
}
If you really want to do exactly what you are asking, you'll have to call IControllerFactory.CreateController(requestContext, controllerName)
instead of new ControllerB()
, but that is a really convoluted way of doing things - I wouldn't recommend it.