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.
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.
If you want to use the same code which is written in a controller action somewhere, I think the better option is to have a C# Class in Business layer and then use the same functionality re-used where-ever needed. In controller action method too have a that class instantiated and call the particular function invoked.
public class BAL.A
{
public void Method(){
/*Implementation here. */
}
}
using BAL;
Public Class HomeCOntroller{
public void Index(){
A objA=new A();
objA.Method();
}
}
I hope this will help to re-use the functionality.
The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.