# System.InvalidOperationException: 传递给 ViewDataDictionary 的模型项类型为 'X'，但此 ViewDataDictionary 实例要求模型项类型为 'Y'。

- **ID:** `dotnet/razor-page-view-data-dictionary`
- **领域:** dotnet
- **类别:** type_error
- **验证级别:** ai_generated
- **修复率:** 95%

## 根因

ASP.NET Core Razor 页面或视图期望类型为 Y 的强类型模型，但控制器或页面处理程序传递了类型为 X 的模型，导致 ViewDataDictionary 中的类型不匹配。

## 版本兼容性

| 版本 | 状态 | 引入 | 弃用 |
|------|------|------|------|
| .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 | — | — |

## 解决方案

1. ```
   确保控制器操作返回正确模型类型的 ViewResult：return View(modelOfTypeY); 其中 modelOfTypeY 的类型与视图的 @model 指令声明的类型一致。
   ```
2. ```
   如果视图必须接受多种类型，将 @model 指令改为 X 和 Y 都实现的基类或接口，然后相应调整视图。
   ```
3. ```
   使用包含 X 和 Y 作为属性的 ViewModel，并将该 ViewModel 传递给视图。
   ```

## 无效尝试

- **Change the @model directive in the view to match the passed type X** — 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. (85% 失败率)
- **Use ViewBag or ViewData to pass the model instead of a strongly-typed model** — This defeats the purpose of strongly-typed views and can lead to runtime casting errors and loss of IntelliSense. (70% 失败率)
- **Cast the model to type Y in the controller** — If X and Y are unrelated types, casting will throw InvalidCastException at runtime. (90% 失败率)
