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()); %>
我无法解释错误消息,但解决此类问题的最佳方法是应用空对象模式: