c# - Razor Safe Navigation Operator? -
is there way navigate object graph in razor view in null-safe manner (without having @if
guard-blocks?
for example, have following in index.cshtml
:
@foreach (store.models.product product in @model) { <tr> <td>@product.id</td> <td>@product.productname</td> <td>@string.format("{0:c}", @product.price)</td> <td>@product.quantity</td> @if (@product.category != null) { <td>@product.category.categoryname</td> } else { <td></td> } </tr> }
not of products have categories. when not, product.category
null.
what safely able navigate object graph , not have worry nullreferenceexception
blowing view.
in groovy/grails, used using safe navigation operator , like:
<td>@product?.category?.categoryname</td>
of course, did not work in razor.
is there sort of equivalent in razor?
one way use inline conditional:
<td>@(product.category != null ? product.category : "")</td>
just makes code more compact
Comments
Post a Comment