当model是父模型上的属性且为null时,强类型部分视图出错

Ric*_*ett 5 asp.net-mvc partial-views

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

传递到字典中的模型项是'ChildClass'类型,但是这个字典需要一个'ParentClass'类型的模型项.

这两个类与此相关:

public class ChildClass { /* properties */ }

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

    /* other properties */
}
Run Code Online (Sandbox Code Playgroud)

我有一个实例ParentClass,其中的价值ChildPropertynull.

我有两个部分视图,ParentView(ViewUserControl<ParentClass>)和ChildView(ViewUserControl<ChildClass>).

在第一个视图中,我有以下...

<% Html.RenderPartial("~/Views/Controls/ChildView.ascx", Model.ChildProperty); %>
Run Code Online (Sandbox Code Playgroud)

这是抛出此帖子顶部列出的异常的行.

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

我可以通过添加仅呈现ChildViewif ChildProperty不为null的代码来解决此问题,但是这一半使得查看失败了.

Rob*_*vey 5

看看这里的答案:使用null模型的renderpartial传递错误的类型

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

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