【问题标题】:The model item passed into the ViewDataDictionary is of type 'System.ValueTuple`2传递到 ViewDataDictionary 的模型项的类型为“System.ValueTuple”2
【发布时间】:2019-07-04 15:03:54
【问题描述】:

我在_ShowComments.cshtml 视图中将模型定义为元组类型,但是当我想调用这个 Partialview 时

当我在Default.cshtml 中调用该方法时出现此错误。

我该如何解决?

错误信息:

InvalidOperationException:传入的模型项 ViewDataDictionary 是类型 'System.ValueTuple`2[System.Collections.Generic.List`1[Jahan.Beta.Web.App.Models.Comment],System.Nullable`1[System.Int32]]', 但是这个 ViewDataDictionary 实例需要一个类型的模型项 'System.ValueTuple`2[System.Collections.Generic.IList`1[Jahan.Beta.Web.App.Models.Comment],System.Nullable`1[System.Int32]]'。

Default.cshtml:

@model List<Comment>

<div class="media mb-4">
    <div class="media-body">
        @Html.Partial("_ShowComments", ValueTuple.Create<List<Comment>, int?>(Model,null))
    </div>
</div>

_ShowComments.cshtml:

@model (IList<Comment> comments, int? parentId)

@if (Model.comments.Any(c => c.ParentId == Model.parentId))
{
    <ul class="list-unstyled">
        @foreach (var childComment in Model.comments.Where(c => c.ParentId == Model.parentId))
        {
            <li class="media">
                @Html.Partial("_ShowComments", (Model.comments, childComment.Id))
            </li>
        }
    </ul>
}

【问题讨论】:

    标签: c# asp.net-core tuples asp.net-core-2.1


    【解决方案1】:

    当视图期望 ValueTuple&lt;IList&lt;Comment&gt;, int?&gt;(注意 ListIList)时,您正在创建 ValueTuple&lt;List&lt;Comment&gt;, int?&gt;,并且编译器将它们视为不同的类型。使用正确的元组类型:

    @Html.Partial("_ShowComments", ValueTuple.Create<IList<Comment>, int?>(Model,null))
    

    或者,在我看来,更简洁的语法:

    @Html.Partial("_ShowComments", ((IList<Comment>)Model,null))
    

    或者,我的首选解决方案是创建一个适当的类来保存值:

    public class ShowCommentsModel
    {
        public IList<Comment> Comments { get; set; }
        public int? ParentId { get; set; }
    }
    

    并切换视图使用:

    @model ShowCommentsModel
    

    【讨论】:

      猜你喜欢
      • 2021-09-21
      • 1970-01-01
      • 2020-01-12
      • 2022-01-17
      • 2020-05-13
      • 2020-10-20
      • 2020-05-10
      • 1970-01-01
      • 1970-01-01
      相关资源
      最近更新 更多