Search code examples
c#asp.net-core-2.1razor-pages

Calling HomeController action with Dependency injection from Razor Page Model


I have an action in HomeController with Dependency Injecttion in Asp.Net Core 2.1.0 Razor Page.

Action Code

    private readonly Test.Data.MyContext _Context;

    public HomeController(Test.Data.MyContext context)
    { _Context = context; }

    [HttpGet]
    public ActionResult TypeofAccounts(string at)
    {
        var result = _Context.TypeOfAccounts
            .Where(x => x.AccountType == at)
            .Select(x =>
                new
                {
                    label = x.AccountType,
                    id = x.AccountType
                }
            );

        return Json(result);
    }

I would like use this result in various Razor PageModel. How can I achieve. Here is sample Razor Page.

public class IndexModel : PageModel
{
    private readonly Test.Data.MyContext _Context;
    public IndexModel(Test.Data.MyContext context)
    { _Context = context; }

    public void OnGet()
    {
        // Here I want bind HomeController's action.
    }
}

I tried with var ta = new Test.Controllers.HomeController().TypeofAccounts("B001"); but no luck.


Solution

  • Though I am not familiar of the practice having an instance of your data context in both view model and controller, you can try this way.

    Controller:

    private readonly Test.Data.MyContext _Context;
    
    public HomeController(Test.Data.MyContext context)
    { _Context = context; }
    
    [HttpGet]
    public ActionResult TypeofAccounts(string at)
    {
        var result = GetTypeOfAccounts(_Context, at);
    
        return Json(result);
    }
    
    public static IQueryable<dynamic> GetTypeOfAccounts(Test.Data.MyContext context, string at)
    {
        var result = context.TypeOfAccounts
            .Where(x => x.AccountType == at)
            .Select(x =>
                new
                {
                    label = x.AccountType,
                    id = x.AccountType
                }
            );
    
        return result;
    }
    

    View Model:

    public class IndexModel : PageModel
    {
        private readonly Test.Data.MyContext _Context;
        public IndexModel(Test.Data.MyContext context)
        { _Context = context; }
    
        public void OnGet()
        {
            // Here I want bind HomeController's action.
            var ta = Test.Controllers.HomeController.GetTypeOfAccounts(_Context, "B001");
        }
    }