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

5

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

传递到字典中的模型项类型为“ChildClass”,但此字典需要一个类型为“ParentClass”的模型项。

这两个类是相关的:

public class ChildClass { /* properties */ }

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

    /* other properties */
}

我有一个ParentClass实例,其中ChildProperty的值为null

我有两个部分视图,ParentViewViewUserControl<ParentClass>)和ChildViewViewUserControl<ChildClass>)。

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

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

这是导致本帖顶部列出的异常的那一行。

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

如果ChildProperty为null,则可以通过添加仅在ChildProperty不为null时呈现ChildView的代码来解决此问题,但这会部分破坏视图的目的。


我无法解释错误信息,但是这类问题的最佳解决方案是应用空对象模式:http://en.wikipedia.org/wiki/Null_Object_pattern - Mark Seemann
1个回答

5

网页内容由stack overflow 提供, 点击上面的
可以查看英文原文,
原文链接