Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

ASP.NET MVC, strongly typed views, partial view parameters glitch

Tags:

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?

like image 619
Arnis Lapsa Avatar asked Jun 26 '09 13:06

Arnis Lapsa


1 Answers

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 ) %> 
like image 120
tvanfosson Avatar answered Sep 28 '22 08:09

tvanfosson