gpt4 book ai didi

c# - 传入 ViewDataDictionary 的模型项的类型为 'System.ValueTuple` 2

转载 作者:太空宇宙 更新时间:2023-11-03 22:32:17 26 4
gpt4 key购买 nike

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

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

我该如何解决?

错误信息:

InvalidOperationException: The model item passed into the ViewDataDictionary is of type 'System.ValueTuple`2[System.Collections.Generic.List`1[Jahan.Beta.Web.App.Models.Comment],System.Nullable`1[System.Int32]]', but this ViewDataDictionary instance requires a model item of type '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>
}

最佳答案

您正在创建一个 ValueTuple<List<Comment>, int?>当 View 期待 ValueTuple<IList<Comment>, int?> 时(注意 ListIList )并且编译器将它们视为不同的类型。使用正确的元组类型:

@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; }
}

并切换 View 使用:

@model ShowCommentsModel

关于c# - 传入 ViewDataDictionary 的模型项的类型为 'System.ValueTuple` 2,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/56890592/

26 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com