c# – Display whitespace for Null value in Views

Question:

When I send some null value to my view , and Razor tries to render the value, an exception is returned. Is there a way, when the view receives a null value, to render it as white space without having to keep doing if checks?

Answer:

Yes.

Suppose for example that @model has a property called Numero that came null for some reason. Good practice to display the value is like this:

@(Model.Numero ?? 0)

This operator has a quaint name: Null coalescence operator . It reads like this:

Use Model.Numero if not null. Otherwise, use 0.

As it is an operator, you can use it for any type of variable, not just integers.

Another option is the conditional ternary operator , which is basically a one-line if-then-else . This one you can use when you need to specify the test to be done:

@(Model.Numero > 0 ? Model.Numero : 0)

That is:

If Model.Numero is greater than zero, use it as the value. Otherwise, use 0.


For whitespace, something like this might work fine:

@(Model.PropertyQuePodeVirNula ?? "")

Or yet:

@(Model.PropertyQuePodeVirNula != null ?? Model.PropertyQuePodeVirNula.ToString() : "")
Scroll to Top