从Razor Page Model进行依赖注入调用HomeController操作

时间:2018-09-19 06:32:41

标签: c# asp.net-core-2.1 razor-pages

我在HomeController中有一个动作,在Dependency Injecttion中有Asp.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中使用此结果。我该如何实现。这是示例剃刀页面。

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");,但没有运气。

1 个答案:

答案 0 :(得分:0)

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

控制器:

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