24
Vote

Html.Partial or RenderPartial with NULL value gets passed the wrong type

description

If I render a partial from a view and pass a null value the base model type gets passed rather than the model / value I actually passed. This is counterintuitive and would force people to pepper their views with an extra 3rd parameter 99% of times. More detailed information in the SO question:

http://stackoverflow.com/questions/650393/asp-net-mvc-renderpartial-with-null-model-gets-passed-the-wrong-type

Please fix!!

comments

FoundationSoft wrote Mar 1, 2012 at 10:44 AM

I have spent several hours on this problem, and I think this is a bug of MVC. Hoping it will be fixed soon.

sazizrahman wrote Mar 29, 2012 at 9:43 PM

I agreed.

christianfredh wrote Mar 30, 2012 at 8:19 AM

Confused me for a couple of hours. Not clear at all what is going on. Would be nice to have a fix!

q42jaap wrote Apr 21, 2012 at 11:43 AM

Though this has been answered, I ran across this and decided I wanted to solve this issue for my project instead of working around it with 'new ViewDataDictionary()'.

I created a set of extension methods:
https://github.com/q42jaap/PartialMagic.Mvc/blob/master/PartialMagic.Mvc/PartialExtensions.cs
I also added some methods that don't call the partial if the model is null, this will save a lot of if statements.

I created them for Razor, but a couple of them should also work with aspx style views (the ones that use HelperResult probably aren't compatible).

The extension methods look like this:
@* calls the partial with Model = null *@
@Html.PartialOrNull("PartialName", null)
@* does not call the partial if the model is null *@
@Html.PartialOrDiscard("PartialName", null)
There are also methods for IEnumerable models and the discard ones can also be called with a Razor lambda that allow you to wrap the partial result with some html.

Feel free to use them if you like.