chiapa
chiapa

Reputation: 4412

Call controller action from non controller class

Is there a way to invoke a controller action from a regular C# class, that is not a controller?

All I found so far uses redirectToAction, but this is controller exclusive.

Upvotes: 3

Views: 4485

Answers (1)

Jason Evans
Jason Evans

Reputation: 29186

A controller is a class like any other, which means you can do this:

var homeController = new HomeController();

(assuming you have your project references setup, I'm not including namespaces in my example, as I don't know what yours are)

Thus you can then execute the methods of that controller via the homeController variable. But, as has been pointed out in the comments, this is not a good design at all. I would strongly recommend you don't do this.

A controller should be called from other controllers, or web requests.

Upvotes: 2

Related Questions