UPDATE The issue was a syntax issue. @awrigley shows the correct way to write this in Razor.
The following works:
@if(Model.Thing.Prop != null)
{
Html.RenderPartial("SomePartialView", Model.Thing.Prop);
}
You have a requirement to show details for the top 1 Foo
for a given Bar
as an HTML table. How do you hide the empty table or show a "none found" message if that Foo
is null?
For example. I'm getting a NullReferenceException
on the following line because Model.Thing.Prop
is null
;
@{Html.RenderPartial("SomePartialView", Model.Thing.Prop);}
It is intentionally null, my Repository returns null instead of a empty Foo
. But this is mildly beside the point, which is that given a null Model.Thing.Prop
, I don't want to call the Html.RenderPartial
.
Update
I've tried the following with no luck:
@if(Model.Thing.Prop != null)
{
@{Html.RenderPartial("SomePartialView", Model.Thing.Prop);}
}
Which results in Visual Studio telling me it's expecting a ;
at line 1, column 1 and also that ;
is an Invalid expression at line 1, column 1 (I'm guessing this is due to the pre-release status of MVC3), and if I hit the page in a browser I get
CS1501: No overload for method 'Write' takes 0 arguments
with the @Html.RenderPartial
line highlighted.
I also tried
@if(Model.Thing.Prop != null)
{
<text>
@{Html.RenderPartial("SomePartialView", Model.Thing.Prop);}
</text>
}
but this results in a NullReferenceException
from within my Partial View, which doesn't seem right. Model.Thing
is definitely a valid Bar
and Model.Thing.Prop
is definitely a null
Foo
.