asp.net-mvc - 当模型是父模型的属性并且为空时,强类型局部 View 出错

标签 asp.net-mvc partial-views

我在调用 Html.RenderPartial 时遇到以下异常:

The model item passed into the dictionary is of type 'ChildClass' but this dictionary requires a model item of type 'ParentClass'.



这两个类与此相关:
public class ChildClass { /* properties */ }

public class ParentClass
{
    public ChildClass ChildProperty { get; set; }

    /* other properties */
}

我有一个 ParentClass 的实例其中 ChildProperty 的值是 null .

我有两个部分 View ,ParentView ( ViewUserControl<ParentClass> ) 和 ChildView (ViewUserControl<ChildClass>)。

在第一个 View 中,我有以下...
<% Html.RenderPartial("~/Views/Controls/ChildView.ascx", Model.ChildProperty); %>

这是引发本文顶部列出的异常的行。

如果ChildProperty,我已经验证了正确的功能。不为空。为什么 MVC 认为这个属性的 null 值是父类型?

我可以通过添加仅呈现 ChildView 的代码来解决此问题。如果 ChildProperty不是空的,但是这一半打败了有观点的观点。

最佳答案

看看这里的答案:renderpartial with null model gets passed the wrong type

如果它有效,您的修复应该如下所示:

<% Html.RenderPartial("~/Views/Controls/ChildView.ascx", Model.ChildProperty, 
      new ViewDataDictionary()); %> 

关于asp.net-mvc - 当模型是父模型的属性并且为空时,强类型局部 View 出错,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/2280757/

相关文章:

c# - asp.net core 3 MVC 上的模型绑定(bind)属性为 null

c# - 通过 MVVM 客户端查看和操作 MVC Web 应用程序的模型

ruby - Rails 从 View 中调用操作

c# - 将 DataAnnotations 添加到自动生成的 DBML 类? MVC 2.0 ASP.NET

c# - 我应该在 MVC 4 中的哪里存储 SQL 查询?

asp.net-mvc - 在 ASP.NET MVC 中自行处理验证失败

c# - MVC 从另一个 MVC 应用程序渲染 (RenderPartial, RenderAction) Html

asp.net-mvc - 部分 View 继承自主布局

c# - 从局部 View 设置主 url 的路由值

c# - (PartialView) 传入字典的模型项是 'Customer' 类型,但是这个字典需要一个 'UserProfile' 类型的模型项