asp.net-core-2.0 - 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();
}
}
解决方案
部分不应有与之关联的 PageModel 文件。如果您有要执行的 C# 代码,您应该考虑创建一个ViewComponent。
或者,您可以将public IList<ImageBE> ImageBE
属性移动到并在该方法中IndexModel
实例化它。OnGetAsync
然后,您可以在部分上指定模型类型,并使用标签助手将其传递给部分,就像您当前正在做的那样:
_ImageGallery.cshtml(部分)
@model IList<ImageBE>
<table class="table">
@foreach (var item in Model) {
...
推荐阅读
- php - Yii2-未定义变量:modelsTraiffSlabs
- wpf - WPF MVVM Caliburn 在特定 ViewModel 中显示所有 ErrorMsgs
- c# - 有一些方法可以防止 Playfab 上的多设备登录吗?
- javascript - React Native Picker 无法将数据值发送到调试器
- sql - 1.找到每个pkey中最大的。2将日期时间“01-24-2020 10:12:12 am”转换为 2020 年 1 月 24 日
- android - 在 NestedScrollView 上带有 onSwipe 处理程序的 MotionLayout
- kubernetes - 在 Kubernetes 中将多个集群角色分配给一个服务帐户会发生什么?
- linux - Raspberry - 无法创建平台 OpenGL 上下文
- google-bigquery - 为数据集创建了外部 Bigquery 配置单元分区表,但无法查看具有分区键的列
- javascript - 如何使用 Bresenham 的直线算法?