I'm attempting to create a generic controller, ie:
public class MyController<T> : Controller where T : SomeType { ... }
However, when I try to use it, I'm running into this error everywhere...
Controller name must end in 'Controller'
So, my question, Is it possible to make a generic controller in asp.net mvc?
Thanks!
Yes, It is possible to share a view across multiple controllers by putting a view into the shared folder. By doing like this, you can automatically make the view available across multiple controllers.
If I understand you properly, what you are trying to do, is route all requests for a given Model through a generic controller of type T.
You would like the T to vary based on the Model requested.
You would like /Product/Index
to trigger MyController<Product>.Index()
This can be accomplished by writing your own IControllerFactory
and implementing the CreateController
method like this:
public IController CreateController(RequestContext requestContext, string controllerName) { Type controllerType = Type.GetType("MyController") .MakeGenericType(Type.GetType(controllerName)); return Activator.CreateInstance(controllerType) as IController; }
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With