9

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

3 Answers 3

11

Try this:

@Html.Partial("Child", null, new ViewDataDictionary<ChildType>(childInstance/*this can be null*/))
Sign up to request clarification or add additional context in comments.

Comments

5

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:

@Html.Partial("Child", new Model())

Since the Model is new, it won't have any values populated.

1 Comment

Sort of. To be more precise, the reason is because, when the view is invoked, there isn't an instance of that Model conceptually. I felt uncomfortable creating and passing an instance of a Model that doesn't exist yet and may not be committed at all just to satisfy the view engine.
1

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

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.