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
?
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
?
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.
Without checking, there’s no way.
0
You can use the null propagation operator, available from the C# 6.0.
Follow the example:
@Model?.Quantidade
Read more about this operator in the documentation: https://docs.microsoft.com/en-us/dotnet/csharp/language-reference/operators/null-conditional-operators.
interesting to update the answer.
Browser other questions tagged c# asp.net-mvc .net
You are not signed in. Login or sign up in order to post.
Show an example of your view code.
– iuristona