使用 Razor 页面模型的依赖注入调用 HomeController 操作

Calling HomeController action with Dependency injection from Razor Page Model

我在 HomeControllerDependency InjecttionAsp.Net Core 2.1.0 Razor Page 有一个动作。

操作代码

    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);
    }

我想在各种 Razor PageModel 中使用这个结果。我怎样才能实现。这是示例 Razor 页面。

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 = new Test.Controllers.HomeController().TypeofAccounts("B001"); 但没有成功。

虽然我不熟悉在视图模型和控制器中都拥有数据上下文实例的做法,但您可以尝试这种方式。

控制器:

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;
}

查看模型:

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");
    }
}