我在调用 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/