Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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

I am working on an ASP.NET MVC 4 application. I use EF 5 with code first and in one of my entities I have :

public string ImageName { get; set; } public string ImageGUIDName { get; set; } 

those two properties which are part of my entity. Since I may not have image uploaded these values can be null but when I render the view passing the model with ImageName and ImageGUIDName coming as null from the database I get this :

Exception Details: System.ArgumentNullException: Value cannot be null.

The basic idea is to provide different text for the user based on the fact if there is picture or not:

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

So when the above code got me that error I tried with string.IsNullOrEmpty(Model.ImageName) and also Model.ImageName.DefaultIfEmpty() != null but I got the exact same error. It seems that I can not just set y entity property as nullable:

public string? ImageName { get; set; } //Not working as it seems 

So how can I deal with this?

like image 574
Leron_says_get_back_Monica Avatar asked Dec 05 '13 19:12

Leron_says_get_back_Monica


People also ask

How do you deal with null models?

In order to simplify your code you should utilize the Null Object pattern. Instead of using null to represent a non existing value, you use an object initialized to empty/meaningless values. This way you do not need to check in dozens of places for nulls and get NullReferenceExpections in case you miss it.


1 Answers

Try this first, you may be passing a Null Model:

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

Otherise, 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> 
like image 128
naspinski Avatar answered Sep 28 '22 06:09

naspinski