# 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`
- **Domain:** dotnet
- **Category:** type_error
- **Verification:** ai_generated
- **Fix Rate:** 95%

## Root Cause

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.

## Version Compatibility

| Version | Status | Introduced | Deprecated |
|---------|--------|------------|------------|
| .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 | — | — |

## Workarounds

1. **Ensure the controller action returns a ViewResult with the correct model type: return View(modelOfTypeY); where modelOfTypeY is of the type declared in the view's @model directive.** (95% success)
   ```
   Ensure the controller action returns a ViewResult with the correct model type: return View(modelOfTypeY); where modelOfTypeY is of the type declared in the view's @model directive.
   ```
2. **If the view must accept multiple types, change the @model directive to a base class or interface that both X and Y implement, then adjust the view accordingly.** (85% success)
   ```
   If the view must accept multiple types, change the @model directive to a base class or interface that both X and Y implement, then adjust the view accordingly.
   ```
3. **Use a ViewModel that contains both X and Y as properties, and pass that ViewModel to the view.** (90% success)
   ```
   Use a ViewModel that contains both X and Y as properties, and pass that ViewModel to the view.
   ```

## Dead Ends

- **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% fail)
- **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% fail)
- **Cast the model to type Y in the controller** — If X and Y are unrelated types, casting will throw InvalidCastException at runtime. (90% fail)
