This question and community wiki answer has been added to assist in closing out numerous unanswered questions as discussed in this meta post.
I have some code and when it executes, it throws an exception saying:
The model item passed into the dictionary is of type Bar but this dictionary requires a model item of type Foo
What does this mean, and how do I fix it?
Best Answer
The error means that you're navigating to a view whose model is declared as typeof
Foo
(by using@model Foo
), but you actually passed it a model which is typeofBar
(note the term dictionary is used because a model is passed to the view via aViewDataDictionary
).The error can be caused by
Passing the wrong model from a controller method to a view (or partial view)
Common examples include using a query that creates an anonymous object (or collection of anonymous objects) and passing it to the view
or passing a collection of objects to a view that expect a single object
The error can be easily identified at compile time by explicitly declaring the model type in the controller to match the model in the view rather than using
var
.Passing the wrong model from a view to a partial view
Given the following model
and a main view declared with
@model Foo
and a partial view declared with@model Bar
, thenwill return the correct model to the main view. However the exception will be thrown if the view includes
By default, the model passed to the partial view is the model declared in the main view and you need to use
to pass the instance of
Bar
to the partial view. Note also that if the value ofMyBar
isnull
(has not been initialized), then by defaultFoo
will be passed to the partial, in which case, it needs to beDeclaring a model in a layout
If a layout file includes a model declaration, then all views that use that layout must declare the same model, or a model that derives from that model.
If you want to include the html for a separate model in a Layout, then in the Layout, use
@Html.Action(...)
to call a[ChildActionOnly]
method initializes that model and returns a partial view for it.