ASP.NET MVC Core 2. 如何避免组件使用与 parent 视图相同的模型?

ASP.NET MVC Core 2. How avoid a component use the same model as the parent view?

我正在创建一个从主视图调用的视图组件(过滤器组件)。

主视图需要一个列表作为模型

@model IEnumerable<Filters>

并在其 header 上调用过滤器 ViewComponent

<vc:my-filter/>

Default.cshtml 组件视图需要 Filter class

@model Filters

然而,当过滤器为 null 时,组件模型从 parent 视图接收相同的模型。并且类型不兼容;

InvalidOperationException: The model item passed into the ViewDataDictionary is of type 'Microsoft.EntityFrameworkCore.Query.Internal.EntityQueryable`1[Item]', but this ViewDataDictionary instance requires a model item of type 'Filters'.

我不想将空 new Filter() 传递给 ViewComponent 视图模型,因为该组件已经实现了一些空验证。

我想不向视图组件发送任何模型。我该怎么做?我只是不想让它访问主页视图模型。

这是 .NET Core v1.1 而非 v2.0 中的重大更改,并且讨论了该行为 here

ViewComponent initial ViewDataDictionary is taken from the calling View. In other terms it is either the same as the View ViewDataDictionary or a clone of it. This makes sense to pass main View error infos, etc. to the ViewComponent.

Now if ViewComponent passes a not null model to the View, the not null model is attached to its ViewDataDictionary, thus causing all Model Metadata to be recomputed to match the new model, so in this case everything works properly.

However, if the model is null, the ViewComponent ViewDataDictionary remains untouched, and is used to create its View ViedDataDictionary. This, in turn means, that the ViewComponent View receives a ViewDataDictionary cloned from the View that called the ViewComponent.

已在 https://github.com/aspnet/Announcements/issues/221 跟踪问题。

此外,您可以使用 中提到的解决方法。