c# - 传递到 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>
}
解决方案
ValueTuple<List<Comment>, int?>
当视图需要 a ValueTuple<IList<Comment>, int?>
(注意List
vs 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
推荐阅读
- typescript - 打字稿:强制排除文件,即使它是导入的
- angular - 父类的 ContentChild
- java - 为什么 LongStream reduce 和 sum 性能之间存在差异?
- c++ - C++对象的不同声明
- c++ - 特征矩阵中的元素智能反转
- arrays - 在电子表格中间插入可变长度的表格-如何使电子表格动态调整
- python-3.x - 在 Pandas Jupyter 中将年、月、日和小时格式化为日期时间对象
- python - 继承公共用户视图 (ODOO 12)
- reactjs - 如何将对象数组传递给Typescript中的类
- android - Ionic Angular Capacitor Android NodeJS - API连接失败