5

I am getting the following exception on a call to Html.RenderPartial:

The model item passed into the dictionary is of type 'ChildClass' but this dictionary requires a model item of type 'ParentClass'.

These two classes are related this:

public class ChildClass { /* properties */ }

public class ParentClass
{
    public ChildClass ChildProperty { get; set; }

    /* other properties */
}

I have an instance of ParentClass where the value of ChildProperty is null.

I have two partial views, ParentView (ViewUserControl<ParentClass>) and ChildView (ViewUserControl<ChildClass>).

In the first view, I have the following...

<% Html.RenderPartial("~/Views/Controls/ChildView.ascx", Model.ChildProperty); %>

This is the line that is throwing the exception listed at the top of this post.

I have verified correct functionality if ChildProperty is not null. Why does MVC think that a null value of this property is of the parent type?

I can workaround this issue by adding code that only renders the ChildView if ChildProperty is not null, but this half defeats the point of having the view.

Richard Ev
  • 52,939
  • 59
  • 191
  • 278
  • I can't explain the error message, but the best solution to these types of problems is to apply the **Null Object pattern** : http://en.wikipedia.org/wiki/Null_Object_pattern – Mark Seemann Feb 17 '10 at 13:05

1 Answers1

5

Have a look at the answer here: renderpartial with null model gets passed the wrong type

If it works, your fix should look like this:

<% Html.RenderPartial("~/Views/Controls/ChildView.ascx", Model.ChildProperty, 
      new ViewDataDictionary()); %> 
Community
  • 1
  • 1
Robert Harvey
  • 178,213
  • 47
  • 333
  • 501