首页 > 解决方案 > Razor PageHandler PartialViewResult 模型类型不匹配

问题描述

我有一个 PartialView ,其类型为 Model ,Machine可在表格中呈现一行。

@model GPT.Core.Models.Machine
<tr>
  @* 
    some html 
  *@
</tr>

当在父视图的循环中呈现时,此部分视图工作正常,如下所示:

@foreach (var machine in pl.Machines)
{
  // some code
  // ...
  await Html.RenderPartialAsync("_MachineTableRow", machine);
}

我在客户端上使用 AJAX-Request 来更新一些数据,并希望此后也更新相应的数据行。所以我的 AJAX 请求调用

public async Task<PartialViewResult> OnPostAnalyzeMachineJournalAsync()
{
    // some code
    // ...
    var machine = GetUpdateMachinePseudoMethod();
    return Partial("_MachineTableRow", machine);
}

但这会引发异常:

System.InvalidOperationException: The model item passed into the ViewDataDictionary is of type 'GPT.Core.Models.Machine', but this ViewDataDictionary instance requires a model item of type 'GPT.Web.Pages.IndexModel'.

我不确定ViewDataDictionary这个异常指的是哪个。但即使它对我没有意义并且只是出于好奇,我也提供IndexModel了例外提到的内容。

await Html.RenderPartialAsync("_MachineTableRow", this);

然后有另一个例外告诉我完全相同的事情,这让我现在完全困惑:

System.InvalidOperationException: The model item passed into the ViewDataDictionary is of type 'GPT.Web.Pages.IndexModel', but this ViewDataDictionary instance requires a model item of type 'GPT.Core.Models.Machine'.

谁能告诉我为什么当我传递一个Machine实例时它不起作用,就像它在部分 cshtml 文件中定义的那样,并且就像它在第二个异常中也提到的那样?我在这里想念什么?

标签: c#asp.net-corepartialrazor-pagesrenderpartial

解决方案


好的,进一步的调查揭示了这一点:

Github 错误修复

似乎这确实是 .netcore 2.2 中的一个错误,并已在 .netcore 3.0 中修复。我将尝试 RC 版本,如果成功,将报告。

编辑:将目标框架更新到 .netcore 3.0 后,代码按预期工作并接受提供的模型。


推荐阅读