Show whitespace for Null value in Views

6

When I send some value null to my view , and Razor tries to render the value, an exception is returned. Is there a way, when view gets a null value, render this as a blank space without having to do checks with if ?

    
asked by anonymous 07.05.2015 / 15:17

2 answers

4

Yes.

Suppose for example that @model has a property called Numero that came null for some reason. The good practice for displaying the value is like this:

@(Model.Numero ?? 0)

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

  

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

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

Another option is the conditional ternary operator , which is basically an if- then-else of a single line. This 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. If not, use 0.

Pro in the case of white space, something like this might suit well:

@(Model.PropertyQuePodeVirNula ?? "")

Or:

@(Model.PropertyQuePodeVirNula != null ?? Model.PropertyQuePodeVirNula.ToString() : "")
    
07.05.2015 / 16:08
0

You can use the null propagation operator, available from C # 6.0 .

Follow the example:

@Model?.Quantidade

Read more about this operator in the documentation: link .

    
18.10.2017 / 13:38