Let's say I have a controller:
public BController : Controller
{
public ActionResult Foo(FooViewModel vm)
{
...
}
}
and at the same time I'm implementing an action in another controller AController where I want to render the result of BController.Foo passing a specific model object. So:
public AController : Controller
{
public ActionResult Bar(BarViewModel vm)
{
FooViewModel fooVm = MakeFooVM(vm);
return ... ; // pass fooVm to BController
}
}
Is there a way to accomplish this in MVC?
An action result is what a controller action returns in response to a browser request. The ASP.NET MVC framework supports several types of action results including: ViewResult - Represents HTML and markup. EmptyResult - Represents no result.
An ActionResult is a return type of a controller method in MVC. Action methods help us to return models to views, file streams, and also redirect to another controller's Action method.
To redirect the user to another action method from the controller action method, we can use RedirectToAction method. Above action method will simply redirect the user to Create action method.
The methods must have different parameters. This is dictated by the programming language and is basically method overloading. Even if two methods have different parameters, they must also have different http verb attributes (httpget, httppost).
Missing a step in the answer above. After you create the controller, you need to set the ControllerContext so that the controller's Request, Response, and HttpContext will be populated. Just creating the controller will result in null values for the controller's context settings.
public AController : Controller
{
public ActionResult Bar(BarViewModel vm)
{
FooViewModel fooVm = MakeFooVM(vm);
var bController = new BController();
bController.ControllerContext = new ControllerContext(this.ControllerContext.RequestContext, bController);
return bController.Foo(fooVm);
}
}
Source: Get ActionResult of another controller-action?
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