views:

131

answers:

1

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.

+2  A: 

Have a look at the answer here: http://stackoverflow.com/questions/650393/asp-net-mvc-renderpartial-with-null-model-gets-passed-the-wrong-type/713921#713921

If it works, your fix should look like this:

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