Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Can the controller take an interface instance as a parameter ? ASP .NET MVC

Tags:

c#

asp.net-mvc

Can a ASP .NET Controller action method take an interface as one of the parameters ?

I would like to have something like:

class MyController 
{
    [HttpPost]
    public ActionResult Action(IMyModel model) {...}
}

Is it possible ? Obviously I would have to tell the framework which concrete implementation of IMyModel that should be instantiated, but how ?

like image 552
driis Avatar asked Mar 20 '10 17:03

driis


People also ask

Can an interface be passed as a parameter C#?

In C#, you are allowed to create a reference variable of an interface type or in other words, you are allowed to create an interface reference variable. Such kind of variable can refer to any object that implements its interface.

Can we have MVC controller with parameterized constructor?

Simply framework will fail to create those controllers object that have parameterized constructor. In that case we need to create controller objects by our self and inject controller parameters there.

Which is the base interface for controllers in ASP.NET MVC?

ASP MVC requires that all controllers implement IController interface. A controller doesn't need to derive from Controller or ControllerBase class. You can find an example of a custom controller implementing the IController interface in Adam Freeman's book.

What does the controller contain in MVC?

A controller is responsible for controlling the way that a user interacts with an MVC application. A controller contains the flow control logic for an ASP.NET MVC application. A controller determines what response to send back to a user when a user makes a browser request.


1 Answers

More or less everything is extensible in ASP.NET MVC so yes; that should be possible. Have a look at Model Binders, I think that is what you're looking for.

like image 84
CodingInsomnia Avatar answered Sep 28 '22 21:09

CodingInsomnia