首页 > 解决方案 > RazorPages:模型没有通过页面模型在部分中实例化

问题描述

我正在测试 RazorPages 和 .Net Core 2.1

我刚刚采用了一个新的项目模板并创建了一个 Partial。这些是文件的相关/添加内容。

我的问题是

1)直接问题:在部分: OnGetAsync(也不是 public void OnGet())没有被调用。我在线查看模型中的 NullReference-exceptiion

@foreach (var item in Model.ImageBE) {

我试图切断 DB-call 并从 contructor 显式调用 OnGet 但没有区别。

2) 我找不到 Page(index) 具有 Partials 模型实例的示例(下面的 ImageGalleryModel)。但这是编译器唯一能接受的。我这样做完全错了吗?

Index.cshtml(页面)

...
[partial name="_ImageGallery" model="Model.ImageGallery" /]
...

索引.cshtml.cs

public class IndexModel : PageModel
    {
        ApplicationDbContext mContext;
        public ImageGalleryModel ImageGallery;

        public IndexModel(ApplicationDbContext context)
        {
            mContext = context;
            ImageGallery = new ImageGalleryModel(mContext);
        }

        public void OnGet()
        {

        }
    }

_ImageGallery.cshtml(部分)

[table class="table"]
    @foreach (var item in Model.ImageBE) {
              ...

_ImageGallery.cshtml.cs

public class ImageGalleryModel : PageModel
    {
        private readonly ApplicationDbContext _context;
        public IList<ImageBE> ImageBE { get; set; }

        public ImageGalleryModel(Photiqo.Data.ApplicationDbContext context)
        {
            _context = context;
        }

        public async Task OnGetAsync()
        {
            ImageBE = await _context.ImageBE.ToListAsync();
        }
    }

标签: asp.net-core-2.0razor-pages

解决方案


部分不应有与之关联的 PageModel 文件。如果您有要执行的 C# 代码,您应该考虑创建一个ViewComponent

或者,您可以将public IList<ImageBE> ImageBE属性移动到并在该方法中IndexModel实例化它。OnGetAsync然后,您可以在部分上指定模型类型,并使用标签助手将其传递给部分,就像您当前正在做的那样:

_ImageGallery.cshtml(部分)

@model IList<ImageBE>

<table class="table">
    @foreach (var item in Model) {
    ...

推荐阅读