How to check model string property for null in a razor view

Try both Model != null and !String.IsNullOrEmpty(Model.ImageName) first, as you may be passing not only a Null value from the Model but also a Null Model:

@if (Model != null && !String.IsNullOrEmpty(Model.ImageName))
{
    <label for="Image">Change picture</label>
}
else
{ 
    <label for="Image">Add picture</label>
}

Otherwise, you can make it even neater with some ternary fun! – but that will still error if your model is Null.

<label for="Image">@(String.IsNullOrEmpty(Model.ImageName) ? "Add" : "Change") picture</label>

Leave a Comment