In ASP.NET MVC and using Razor, I have a View (parent) calling another View (child) as partial. Both are strongly typed but they have a different Model type.
Normally, in these situations, we pass a Model explicitly from the parent View to the child View.
@Html.Partial("Child", Model)
We can also choose not to specify explicitly a Model to be passed and, in those cases, the parent View will attempt to pass its own Model to the child View. This works if the types match and it is desirable in most cases.
@Html.Partial("Child")
In my case, however, I really want the parent View not to try to pass anything to the child View. How would I do that?
I thought of attempting to pass null
explicitly:
@Html.Partial("Child", null)
But this still passes the parent's Model to the child View, resulting in an error: The model item passed into the dictionary is of type 'A', but this dictionary requires a model item of type 'B'.
(As a side note, the child View is a Create View for its model, that's why I don't have an instance to pass to it.)
Try this:
I understand the reason you want to not pass the model is so that your inputs are emptied out? If this is the case, you can rather pass a new Model to this partial:
Since the Model is new, it won't have any values populated.
You could have your create form not strongly typed... craft your inputs in order to once posted you will have a model binded in your controller action.
Now... for me it doesn't worth the work just for the conceptual subtlety of "Model not existing yet" (AKA not in database yet).
In my case I create dummy models just to set default values in certain fields (for instance: setting today date, default values in dropdownlists, etc.)