Home > Enterprise >  How to invoke method of a controller from another one?
How to invoke method of a controller from another one?

Time:12-02

I want to call a method of controller A from controller B and get its return value.

How can I do that?

ControllerA:

[HttpGet]
public async Task<ParentModel> GetParentModel(string contractNumberPar)
{
    try
    {
        // (...) - some code
        var viewModel = new ParentModel
        {
            // (...) - some code
        };
    
        return viewModel;
    }
    catch (Exception ex)
    {
        throw;
    }
}

ControllerB:

ParentModel viewModel = RedirectToAction(
                       "ControllerA",
                       "GetParentModel",
                       new
                       {
                           contractNumberPar = contractNumber
                       });

Error message:

Cannot implicitly convert type microsoft.aspnetcore.mvc.redirecttoaction to (....).ParentModel

CodePudding user response:

You'd better create a common service,so that you can reuse it in both A and B controllers,here is a demo:

service:

public class MyService
{
    public async Task<ParentModel> GetParentModel(string contractNumberPar)
    {
        try
        {
            // (...) - some code
            var viewModel = new ParentModel
            {
                // (...) - some code
            };

            return viewModel;
        }
        catch (Exception ex)
        {
            throw;
        }
    }
}

register the service(before .net6 in Startup.cs):

services.AddScoped<MyAccountService>();

register the service(.net6,.net7 in Program.cs):

builder.Services.AddScoped<MyService>();

BController:

public class BController : Controller
    {
        private readonly MyService MyService;

        public BController(MyService myService)
        {
            MyService = myService;
        }
        public async Task<IActionResult> IndexAsync()
        { 
            string contractNumber="1";
            ParentModel viewModel = await MyService.GetParentModel(contractNumber);
            return Ok(viewModel);
        }
        
    }
  • Related