Warning: file_get_contents(/data/phpspider/zhask/data//catemap/0/asp.net-mvc/16.json): failed to open stream: No such file or directory in /data/phpspider/zhask/libs/function.php on line 167

Warning: Invalid argument supplied for foreach() in /data/phpspider/zhask/libs/tag.function.php on line 1116

Notice: Undefined index: in /data/phpspider/zhask/libs/function.php on line 180

Warning: array_chunk() expects parameter 1 to be array, null given in /data/phpspider/zhask/libs/function.php on line 181
Asp.net mvc 当模型是父模型上的属性且为空时,强类型局部视图出错_Asp.net Mvc_Partial Views - Fatal编程技术网

Asp.net mvc 当模型是父模型上的属性且为空时,强类型局部视图出错

Asp.net mvc 当模型是父模型上的属性且为空时,强类型局部视图出错,asp.net-mvc,partial-views,Asp.net Mvc,Partial Views,我在调用Html.RenderPartial时遇到以下异常: 传递到字典中的模型项的类型为“ChildClass”,但此字典需要“ParentClass”类型的模型项 这两个类别与此相关: public class ChildClass { /* properties */ } public class ParentClass { public ChildClass ChildProperty { get; set; } /* other properties */ } 我

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

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

这两个类别与此相关:

public class ChildClass { /* properties */ }

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

    /* other properties */
}
我有一个
ParentClass
的实例,其中
ChildProperty
的值是
null

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

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

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

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

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


如果
ChildProperty
不为空,我可以通过添加只呈现
ChildView
的代码来解决这个问题,但这一半的代码不符合拥有视图的观点。

看看这里的答案:

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

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

我无法解释错误消息,但解决此类问题的最佳方法是应用空对象模式: