dotnet type_error ai_generated true

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

Also available as: JSON · Markdown · 中文
95%Fix Rate
88%Confidence
1Evidence
2023-03-10First Seen

Version Compatibility

VersionStatusIntroducedDeprecatedNotes
.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

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.

generic

中文

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

Official Documentation

https://learn.microsoft.com/en-us/aspnet/core/mvc/views/overview

Workarounds

  1. 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.
    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. 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.
    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. 90% success Use a ViewModel that contains both X and Y as properties, and pass that ViewModel to the view.
    Use a ViewModel that contains both X and Y as properties, and pass that ViewModel to the view.

中文步骤

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

Dead Ends

Common approaches that don't work:

  1. Change the @model directive in the view to match the passed type X 85% fail

    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.

  2. Use ViewBag or ViewData to pass the model instead of a strongly-typed model 70% fail

    This defeats the purpose of strongly-typed views and can lead to runtime casting errors and loss of IntelliSense.

  3. Cast the model to type Y in the controller 90% fail

    If X and Y are unrelated types, casting will throw InvalidCastException at runtime.