使用带有DBContext依赖项注入的partialview模型实例在_layout.cshtml中渲染Partial View [英] Render a Partial View in _layout.cshtml using the partialview model instance with DBContext dependency injection

查看:75
本文介绍了使用带有DBContext依赖项注入的partialview模型实例在_layout.cshtml中渲染Partial View的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

首先,我想说我是Asp.net Core的新手,并且还具有依赖项注入(DI)的概念.我正在阅读许多试图理解它的文章,所以我需要耐心.

At first I'd like to say I'm new to Asp.net Core and also with concepts of dependency injection (DI). I'm reading a lot trying understand it, so I ask for patience.

我正在尝试Razor页面(不是MVC),我的目标是将"_layout.cshtml"呈现为局部视图,在该视图中,使用实体框架获得的信息在所有页面上均可用.

I'm trying Razor Pages (not MVC) and my goal is to render to "_layout.cshtml" a partial view, in which information obtained using the Entity Framework is available on all pages.

我将DBContext添加到Startup.cs文件中,如下所示:

I added the DBContext in the Startup.cs file as follows:

  services.AddDbContext <AppDBContext> (options =>
  options.UseSqlServer (Configuration.GetConnectionString ("AppDBContext")

在MenuPartial.cshtml.cs的"PageModel"中

And in "PageModel" for MenuPartial.cshtml.cs

 public class MenuPartialModel: PageModel
    {
       
       private readonly AppDBContext _db;
      

        public MenuPartialModel (AppDBContext db)      
        {
            _db = db;
        }
                 
}

在_layout.cshtm文件中,我尝试了几种使用新模型实例调用PartialAsync的方法:

In the _layout.cshtm file I tried several ways to call PartialAsync with the instance of a new model:

如果像下面这样设置新的实例模型,我将使用不带参数的构造函数,因此不会注入DbContext

If set new instance model like bellow I'll be using constructor without parameters, therefore the DbContext is not injected

@await Html.PartialAsync ("MenuPartial", new MenuPartialModel ())

我还考虑过使用:

@await Html.PartialAsync ("MenuPartial", new MenuPartialModel (new AppDBContext ())

我认为这不是正确的方法.因为如果DbContext是自动注入的,为什么我应该通过再次传递连接参数来执行新实例?

I believe that wouldn't be a correct approach. Because if the DbContext was injected automatically, why should I perform a new instance by passing connection parameters again?

实现我的目标的最佳方法是什么?我考虑过使用ViewComponents,但是,起初我想了解是否有任何方法可以实例化模型并使用注入DBContext的构造函数.

What would be the best approach to achieve my goal? I thought about using ViewComponents, however, at first I would like to understand if there is any way to instantiate a model and use the constructor that injects the DBContext.

推荐答案

我想了解是否可以实例化模型并使用注入DBContext的构造函数.

I would like to understand if there is any way to instantiate a model and use the constructor that injects the DBContext.

在ASP.NET Core MVC中,普通的旧CLR类(POCO)不参与ASP.NET Core依赖注入. MenuPartialModel 是POCO(与大多数MVC模型一样).结果,该框架不会自动将依赖项注入其中.

In ASP.NET Core MVC, plain old CLR classes (POCOs) do not participate in ASP.NET Core Dependency Injection. The MenuPartialModel is a POCO (as are most MVC models). As a result, the framework will not automatically inject dependencies into it.

一些内置的ASP.NET Core MVC类被连接到依赖项注入中.其中包括(但不限于):

Some built-in ASP.NET Core MVC classes are wired into the dependency injection. These include (but are not limited to):

  • 控制器,
  • 标记助手,
  • 剃刀视图
  • 剃刀纸页和
  • 查看组件.

MVC中的规范方法是将依赖项(即服务)注入其中之一,然后将任何数据手动传递给POCO模型.

The canonical approach in MVC is to inject dependencies (aka services) into one of those, and then to pass any data manually to the POCO model.

什么是[好的]方法来实现我的目标?

What would be [a good] approach to achieve my goal?

我将使用查看组件.视图组件就像具有模型,视图和控制器的局部视图.

Instead of Partial View, I would use a View Component. A view component is like a partial view that has a model, a view, and a controller.

控制器是 InvokeAsync ,它没有公开给HTTP,但它仍然是控制器

The controller is InvokeAsync, which isn't exposed to HTTP, but it is still a controller in the traditional sense, because it is responsible for binding the model to the view.

using System.Threading.Tasks;
using Microsoft.AspNetCore.Mvc;
using MyApplication.Data;

public class MenuModel
{
    public string MyProperty { get; set; }
    public string MyOtherProperty { get; set; }
}

public class MenuViewComponent : ViewComponent
{
    private readonly ApplicationDbContext dbContext;

    public MenuViewComponent(ApplicationDbContext dbContext)
    {
        this.dbContext = dbContext;
    }

    public async Task<IViewComponentResult> InvokeAsync()
    {
        var data = await dbContext...

        var model = new MenuModel 
        {
            MyProperty = data.FirstValue,
            MyOtherProperty = data.OtherValue,
        };

        return View(model);
    }
}

您还需要在这些位置之一中使用Razor文件作为视图.

You will also need a Razor file at one of these locations to act as the view.

/Pages/Shared/Components/Menu/Default.cshtml
/Views/Shared/Components/Menu/Default.cshtml

Default.cshtml 文件将包含以下内容:

That Default.cshtml file will contain something like this:

@model MenuModel

<p>@Model.MyProperty</p>
<p>@Model.MyOtherProperty</p>

使用视图组件

@await Component.InvokeAsync("Menu")

使用AJAX访问View组件

开箱即用,View组件不公开给HTTP.要通过AJAX访问它们,我们需要

这篇关于使用带有DBContext依赖项注入的partialview模型实例在_layout.cshtml中渲染Partial View的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆