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

22 浏览
0 Comments

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

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

传入字典的模型项的类型为'ChildClass',但该字典需要一个模型项的类型为'ParentClass'。

这两个类是相关的:

public class ChildClass { /* 属性 */ }
public class ParentClass
{
    public ChildClass ChildProperty { get; set; }
    /* 其他属性 */
}

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

我有两个局部视图,ParentView (ViewUserControl) 和 ChildView (ViewUserControl)。

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

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

这是引发此帖子顶部列出的异常的代码行。

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

我可以通过添加代码来解决此问题,只有在ChildProperty不为空时才渲染ChildView,但这在一定程度上违背了使用视图的初衷。

0
0 Comments

当使用强类型的部分视图,且模型是父模型的属性且为null时,可能会出现错误。解决方法是使用Html.RenderPartial方法,并通过ViewDataDictionary传递一个空的ViewData对象。

具体解决方法可以参考这里的回答:renderpartial with null model gets passed the wrong type。如果按照这个方法来解决,代码应该如下所示:

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

通过上述方法,可以解决在模型为null时使用强类型的部分视图时出现的错误。

0