Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

What is the correct pattern to protect against NullReferenceExceptions in ASP.NET MVC

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.

like image 426
Greg B Avatar asked Nov 05 '22 06:11

Greg B


1 Answers

I presume you don't want to use...

@if (Model.Thing.Prop != null)
{Html.RenderPartial("SomePartialView", Model.Thing.Prop);} 

...because you still want to render part of the partial view?

Oh, no. Have read your post properly.

I have no idea why the above code doesn't work for you.

EDIT:

Remember that in Razor, @ can be used two ways:

  1. To execute statements:

    @{ MyStatement; }

  2. To evaluate an HtmlHelper, a class method, property or variable that returns a string of some form or other (eg, HtmlString, MvcHtmlString or string). For example:

    @MyClass.MyStringProperty

Note that in case 2, no terminating semi colon is required.

1 and 2 indicate that if you have an htmlhelper that returns something other than a string (eg, void), then you have to call it as follows:

@{Html.MyHelperThatReturnsVoid;}

Whereas with an HtmlHelper that returns a string or HtmlString or MvcHtmlString, you can simply write:

@Html.MyHelperThatReturnsAString

For more detail, see the accepted answer to a question I asked:

Custom HtmlHelper that returns void problem


like image 138
awrigley Avatar answered Nov 10 '22 16:11

awrigley