MVC: model of type Nullable <T>
I have a partial view that inherits from ViewUserControl<Guid?>
- that is, the model has a type Nullable<Guid>
. Very simple look, nothing special, but that's not the point.
Somewhere else, I Html.RenderPartial( "MyView", someGuid )
, where someGuid
has a type Nullable<Guid>
. Everything is perfectly legal, should work fine, right?
But here getcha: the second argument Html.RenderPartial
is of type object
, and therefore Nullable<Guid>
is the type of the value, it should be boxed. But nullable types are somehow special in the CLR, so when you insert one, you actually end up with either the boxed value of the type T
(the Nullable argument), or null if nullable doesn't matter to start with. And this last case is really interesting.
It turns out that sometimes I have a situation where someGuid.HasValue == false
. And in these cases, I do get a call Html.RenderPartial( "MyView", null )
. And what does the HtmlHelper do when the model is null? Believe it or not, he just goes ahead and takes the parenting gaze model. Regardless of this type.
So, in such cases I get an exception: "The model item passed to the dictionary is of type" Parent.View.Model.Type ", but this dictionary requires a model item of type" System ". Guid?"
So the question is, how do I make MVC pass correctly new Nullable<Guid> { HasValue = false }
instead of trying to grab the parent model?
Note . I was considering transferring my Guid?
to a different type of object specially created for this, but that seems downright ridiculous. You don't want to do this as long as there is another way.
Note 2 : Now that I've written all of this, I realized that the question can be boiled down to how to pass null for the model without ending up with the parent model?
a source to share
<% Html.RenderPartial("MyView", someGuid ?? new Guid()); %>
UPDATE:
By using the editor and / or display templates in ASP.NET MVC 2.0, you can achieve the desired result. Place the file Guid.ascx
in a folder Shared/EditorTemplates
and include it like this:
<%= Html.EditorFor(x => someGuid) %>
or if guid is a property of the main model:
<%= Html.EditorFor(x => x.SomeGuid) %>
Now, if you put <%= Model.HasValue %>
inside a partial, you can get false
, but not with RenderPartial
.
a source to share