当模型是父模型的属性且为 null 时,强类型分部视图会出现错误
我在调用 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 认为该属性的 null 值属于父类型?
我可以通过添加仅在 ChildProperty
不为 null 时呈现 ChildView
的代码来解决此问题,但这一半破坏了拥有视图的意义。
I am getting the following exception on a call to Html.RenderPartial
:
The model item passed into the dictionary is of type 'ChildClass' but this dictionary requires a model item of type 'ParentClass'.
These two classes are related this:
public class ChildClass { /* properties */ }
public class ParentClass
{
public ChildClass ChildProperty { get; set; }
/* other properties */
}
I have an instance of ParentClass
where the value of ChildProperty
is null
.
I have two partial views, ParentView
(ViewUserControl<ParentClass>
) and ChildView
(ViewUserControl<ChildClass>
).
In the first view, I have the following...
<% Html.RenderPartial("~/Views/Controls/ChildView.ascx", Model.ChildProperty); %>
This is the line that is throwing the exception listed at the top of this post.
I have verified correct functionality if ChildProperty
is not null. Why does MVC think that a null value of this property is of the parent type?
I can workaround this issue by adding code that only renders the ChildView
if ChildProperty
is not null, but this half defeats the point of having the view.
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(1)
看看这里的答案:带有 null 模型的 renderpartial 传递了错误的类型
如果有效,您的修复应该如下所示:
Have a look at the answer here: renderpartial with null model gets passed the wrong type
If it works, your fix should look like this: