View Component - 传递到 ViewDataDictionary 的模型不正确



我正在尝试将一些数据传递到我的布局中,但无法使其正常工作。我以前成功地做到了这一点,但这一次,无论我尝试什么,它都不起作用。

我收到此错误:

InvalidOperationException:传递到 ViewDataDictionary 的模型项的类型为 'System.Collections.Generic.List'1[DOOR.Core.Web.Models.DataTaxonomy.Object]",但此 ViewDataDictionary 实例需要类型为"DOOR"的模型项。Core.Web.Pages.DataTaxonomyTool.IndexModel'.

过去有人处理过类似的事情吗?

My Default.cshtml:

@model DOOR.Core.Web.Pages.DataTaxonomyTool.IndexModel
@addTagHelper *, Microsoft.AspNetCore.Mvc.TagHelpers
@{
Layout = "~/Pages/DataTaxonomyTool/Layout/LayoutTaxonomy.cshtml";
}   
@for (char c = 'A'; c <= 'Z'; c++)
{
<ul style="list-style:none">
<li class="nav-item">
<a class="nav-link" data-toggle="collapse" data-target="#@c.ToString().ToLower()">@c</a>
<div id="@c.ToString().ToLower()" class="collapse">
@foreach (var item in Model.Object.OrderBy(x => x.ObjectName))
{
@if (item.ObjectName.StartsWith(c.ToString().ToLower()))
{
<ul style="list-style:none">
<li>@item.ObjectName</li>
</ul>
}
}
</div>
</li>
</ul>
}

我的视图组件类:

public class LayoutListsViewComponent : ViewComponent
{
DOOR.Core.Web.Models.ReportContext _context;
public LayoutListsViewComponent(DOOR.Core.Web.Models.ReportContext context)
{
_context = context;
}
public IList<Object> objects { get; set; }
public async Task<IViewComponentResult> InvokeAsync()
{
var objects = await _context.objects.ToListAsync();
return View(objects);
}
}

"我的布局"页面:

addTagHelper*,DOOR.Core.Web
<!DOCTYPE html>
<html>
...
<vc:layout-lists></vc:layout-lists>
...

您返回不同的对象进行查看,而您的视图使用不同的对象进行强类型。显然,看起来您忘记将返回IndexModel并填充Object属性。

正如您的视图@model DOOR.Core.Web.Pages.DataTaxonomyTool.IndexModel,而您返回的是某种Object类型的集合,即System.Collections.Generic.List1[门。Core.Web.Models.DataTaxonomy.Object]',这显然是行不通的。

您可能需要以下内容:

IndexModel model = new IndexModel();
model.Object = await _context.objects.ToListAsync();
return View(model);

我们无法查看类型,但很明显,返回到视图的模型不属于预期的类型。

放置一些断点并查看要返回的内容,您需要从该断点转换为

DOOR.Core.Web.Pages.DataTaxonomyTool.IndexModel

我还有一件事,我对返回视图时使用异步有严重的怀疑。如果我是你,我不会这样做,当你想要获取数据时使用它,但在你返回视图时不使用它

最新更新