加入收藏 | 设为首页 | 会员中心 | 我要投稿 李大同 (https://www.lidatong.com.cn/)- 科技、建站、经验、云计算、5G、大数据,站长网!
当前位置: 首页 > 编程开发 > asp.Net > 正文

asp.net-mvc – 当model是父模型上的属性且为null时,强类型局部

发布时间:2020-12-16 06:57:02 所属栏目:asp.Net 来源:网络整理
导读:我在调用 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 *
我在调用 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.

我有两个部分视图,ParentView(ViewUserControl< ParentClass>)和ChildView(ViewUserControl< ChildClass>).

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

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

这是抛出此帖子顶部列出的异常的行.

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

我可以通过添加仅在ChildProperty不为null的情况下呈现ChildView的代码来解决此问题,但是这一半使得查看失败了.

解决方法

看看这里的答案: renderpartial with null model gets passed the wrong type

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

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

(编辑:李大同)

【声明】本站内容均来自网络,其相关言论仅代表作者个人观点,不代表本站立场。若无意侵犯到您的权利,请及时与联系站长删除相关内容!

    推荐文章
      热点阅读