System.InvalidOperationException: 传递给 ViewDataDictionary 的模型项类型为 'X',但此 ViewDataDictionary 实例要求模型项类型为 'Y'。
System.InvalidOperationException: The model item passed into the ViewDataDictionary is of type 'X', but this ViewDataDictionary instance requires a model item of type 'Y'.
ID: dotnet/razor-page-view-data-dictionary
版本兼容性
| 版本 | 状态 | 引入 | 弃用 | 备注 |
|---|---|---|---|---|
| .NET 6.0 | active | — | — | — |
| .NET 7.0 | active | — | — | — |
| .NET 8.0 | active | — | — | — |
| ASP.NET Core 6.0 | active | — | — | — |
| ASP.NET Core 7.0 | active | — | — | — |
| ASP.NET Core 8.0 | active | — | — | — |
根因分析
ASP.NET Core Razor 页面或视图期望类型为 Y 的强类型模型,但控制器或页面处理程序传递了类型为 X 的模型,导致 ViewDataDictionary 中的类型不匹配。
English
ASP.NET Core Razor Page or View expects a strongly-typed model of type Y, but the controller or page handler passes a model of type X, causing a type mismatch in ViewDataDictionary.
官方文档
https://learn.microsoft.com/en-us/aspnet/core/mvc/views/overview解决方案
-
确保控制器操作返回正确模型类型的 ViewResult:return View(modelOfTypeY); 其中 modelOfTypeY 的类型与视图的 @model 指令声明的类型一致。
-
如果视图必须接受多种类型,将 @model 指令改为 X 和 Y 都实现的基类或接口,然后相应调整视图。
-
使用包含 X 和 Y 作为属性的 ViewModel,并将该 ViewModel 传递给视图。
无效尝试
常见但无效的做法:
-
Change the @model directive in the view to match the passed type X
85% 失败
This breaks the view's contract with its expected model type; the view may use properties of Y that don't exist on X, causing runtime errors.
-
Use ViewBag or ViewData to pass the model instead of a strongly-typed model
70% 失败
This defeats the purpose of strongly-typed views and can lead to runtime casting errors and loss of IntelliSense.
-
Cast the model to type Y in the controller
90% 失败
If X and Y are unrelated types, casting will throw InvalidCastException at runtime.