Show white space for Null value in Views

Asked

Viewed 328 times

6

When I send some value null for my view, and Razor tries to render the value, is returned a Exception. There is a way when the view receive a value null, render this as a blank space without having to run checks with if?

  • Show an example of your view code.

2 answers

4

Yes.

Suppose, for example, that @model has a property called Numero which came void for some reason. Good practice for displaying the value is like this:

@(Model.Numero ?? 0)

This operator has a picturesque name: Operator of null coalescence. It reads like this:

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

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

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

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

That is to say:

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


For the case of white space, something like this can suit well:

@(Model.PropertyQuePodeVirNula ?? "")

Or else:

@(Model.PropertyQuePodeVirNula != null ?? Model.PropertyQuePodeVirNula.ToString() : "")
  • Opa, I did not specify very well the question. I would like to do this without having to do checks with if, for example.

  • 1

    Without checking, there’s no way.

0

  • interesting to update the answer.

Browser other questions tagged

You are not signed in. Login or sign up in order to post.