Asp.net-mvc – ASP.NET MVC, strongly typed views, partial view parameters glitch

asp.net-mvcnullstrongly-typed-view

If i got view which inherits from:

System.Web.Mvc.ViewPage<Foo>

Where Foo has a property Bar with a type string
And view wants to render strongly typed partial view which inherits from:

System.Web.Mvc.ViewUserControl<string>  

like this:

Html.RenderPartial("_Bar", Model.Bar);%>

Then why it will throw this:

The model item passed into the dictionary is of type 'Foo'
but this dictionary requires a model item of type 'System.String'.

when bar is not initialized?

More specific: why it passes Foo, where it should pass null?

Best Answer

As @Dennis points out, if the model value is null, it will use the existing model from the view. The reason for this is to support the ability to call a partial view using a signature that contains only the partial view name and have it reuse the existing model. Internally, all of the RenderPartial helpers defer to a single RenderPartialInternal method. The way you get that method to reuse the existing model is to pass in a null value for the model (which the signature that takes only a view name does). When you pass a null value to the signature containing both a view name and a model object, you are essentially replicating the behavior of the method that takes only the view name.

This should fix your issue:

<% Html.RenderPartial( "_Bar", Model.Bar ?? string.Empty ) %>