I came across an error statement in MVC that pointed me in the wrong direction. Since it wasn't apparent from the error statement what the true error was, I decided to post my experience here so that others might learn from my experience.
One of the many great features in ASP.NET MVC is the ability to load partial views in a very simple manner. In fact, it is so simple that when one of my coworkers had an issue doing just that, I was initially stumped. Everything looked great but he was getting an InvalidOperationException error that said “The model item passed into the dictionary is of type ‘x’, but this dictionary requires a model item of type ‘y’.” The model for the parent page worked just fine and if we loaded the partial view as a full view (we had two copies of the same view for testing purposes), everything worked.
I was able to recreate the issue in a test project (which I included in the above download link). In my test project, I have a model with First and Last Name and a Phone Number model. The Phone Number model contains the phone number and the description of the number. That is all there is to my data. In my Index view, I display the main model and then have a partial view that renders my phone number model. In the real world, this would be much more complicated but for our purposes, it worked just fine.
In my Home controller, I initialize the main model, pass in a first and last name, and return the View with the strongly-typed model attached. Immediately, I get the same error as my coworker. Here is an image of the error I receive:
Now that I had something to work with, I started playing around with what was happening. First, I know I didn’t pass in phone number information. If I do that, everything works well. However, what if I want the user to add phone number information? Well, it turns out the solution is obvious even if the error statement isn’t: I still need to initialize the Phone Number model. Passing a null value or an uninitialized model will throw the error we see here.
In the end, the solution was simple but the error message sent me down the wrong path. I spent my initial steps looking into why it was getting the wrong model when the real issue was that I was not passing in a valid model. To solve my issue, I simply initialized the Phone Number model in my main model's constructor method. When you open the attached solution, these lines are commented out so that you can see the error. To solve the error, go to the PersonModel.cs file and uncomment the method found there.
August 21, 2012 - Initial Version