views:

137

answers:

2

I've got a viewpage with the inherits part looking like

Inherits="System.Web.Mvc.ViewPage<User>"

and a ViewUserControl with the inherits part looking like

Inherits="System.Web.Mvc.ViewUserControl<Address>

where User class (shortened) essentially looks like:

class User {
public virtual Address address { get; set; }

}

Now, if I try:

Html.RenderPartial("Address", Model.address);

then I potentially get some strange behaviour. In my case, it turns out Model.address was null Instead of passing null to the control, it looks like the framework tried to pass Model (i.e type=User) and was throwing an error (unexpected type).

Disregarding the fact that my address was null, is that behaviour of defaulting to the parent object a bug, or expected behaviour. If it is expected behaviour then can someone please explain why? I don't get it.

+1  A: 

Very often these kinds of questions result in the OP making a mistake elsewhere, and the error isn't reproducible. I tried recreating your exact scenario, and what do you know? You're actually right :) I created a simple Parent / Child relationship and had the View be of type child, and the partial of type child.Parent that was null, and I didn't get a null reference, I did in fact get the type mismatch error. In fact, even if explicitly passed null on to the view:

Html.RenderPartial("MyPartial",null);

or even with a direct cast:

Html.RenderPartial("MyPartial",(Parent)null);

it still gave the mismatch error.

My guess and this really is a total guess, is that when it detects that the object being passed in is null, it just defaults to using the Model of the actual view itself. I'm not sure either if this is by design or a bug, but that's the only thing that makes sense.

BFree
Thanks for confirming the behaviour. At least I know now its not just me. Lets hope someone has an answer. +1 for effort you went to :-)
David Archer
A: 

I believe you should avoid passing null Models to your Views. Use default/empty Model if your Model is null. This should work:

Html.RenderPartial("Address", Model.address ?? new Address { /* OPTIONAL: default values */});
eu-ge-ne
Agreed, but I'm more curious about the behaviour whereby it defaults to the 'User' model :-(
David Archer