Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Error with strongly-typed partial view when model is a property on a parent model and is null

Tags:

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.

like image 686
Richard Ev Avatar asked Feb 17 '10 13:02

Richard Ev


1 Answers

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()); %> 
like image 168
Robert Harvey Avatar answered Oct 12 '22 12:10

Robert Harvey