Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to prevent view from passing its model to the partial view, but instead pass null?

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

like image 745
Theodoros Chatzigiannakis Avatar asked Jun 24 '13 20:06

Theodoros Chatzigiannakis


1 Answers

Try this:

@Html.Partial("Child", null, new ViewDataDictionary<ChildType>(childInstance/*this can be null*/))
like image 106
Max Toro Avatar answered Jan 03 '23 15:01

Max Toro