首页 > 解决方案 > 传递到 ViewDataDictionary 的模型项的类型为“System.ValueTuple”2

问题描述

我已将_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]]'。

默认.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-coretuplesasp.net-core-2.1

解决方案


ValueTuple<List<Comment>, int?>当视图需要 a ValueTuple<IList<Comment>, int?>(注意Listvs IList)并且编译器将它们视为不同的类型时,您正在创建 a 。使用正确的元组类型:

@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

推荐阅读