【问题标题】:Razor PageHandler PartialViewResult Model Type mismatchRazor PageHandler PartialViewResult 模型类型不匹配
【发布时间】:2019-09-20 06:44:02
【问题描述】:

我有一个带有 Machine 类型的模型的 PartialView,它在表格中呈现一行。

@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文件中定义的那样,就像第二个例外中提到的那样?我在这里错过了什么?

【问题讨论】:

  • 这个异常究竟是在哪里产生的?里面OnPostAnalyzeMachineJournalAsync()?
  • 不,在Microsoft.AspNetCore.Mvc.ViewFeatures.ViewDataDictionary.EnsureCompatible(Object value) 见我的回答,看来这确实是框架中的一个错误。
  • 好的,我会的,谢谢。

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


【解决方案1】:

好的,进一步调查发现:

Github Bugfix

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

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

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 2014-02-05
    • 2019-02-27
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2011-07-26
    • 2020-10-18
    相关资源
    最近更新 更多