I'm trying to detect if a list which is in a model contains any objects, if it does then it will execute code in the razor view, if it doesn't it should skip the code. I am witnessing some unusual behaviour that i cant get to the bottom of. The null check is ignored and the code inside the if statement is being validated even though the if statement is false when debugging.
Model contains a list of details pertaining to a user. The model also has other attributes e.g
Public List<UserDetails> User {get;set;}
Public List<CompanyDetails> Companies {get;set;}
Controller does not pass anything into this list (list is not initialised) to the view, so just an instance of the model. On the view I try to use an if statement to toggle html depending on if this list isn't null, in this case toggling the display of the users details:
if(Model.User != null){
//do something with the list of objects in html
}
The if statement returns "false" therefore it should not execute the code inside the if statement. However i am getting a Null Reference Exception and the compiler throws an error from inside the if statement (when putting a break-point in the razor view).
I have tried different approaches for example making an instance of the object e.g an empty list on the controller
var Model = new UserLocatorModel();
Model.User=new List<UserDetails>();
and change the code to:
if(Model.User.Count() != 0){
//do something with the list of objects in html
}
But this introduces the System.ArgumentOutOfRangeException
Lastly, if i add an empty class object to the new list, i introduce more issues as now i need to enter the list and check an item in the object to see if it exists.
Code example
//model UserLocatorModel
public class UserModel(){
public List<Detail> User {get;set;}
Public List<CompanyDetails> Companies {get;set;}
}
//view
@Model Project.Models.UserLocatorModel
@if(Model.User != null){
//do something
}
I want to be able to detect the null list and skip the code inside the if statement which sounds basic enough. Thanks in advance
::Edit. This is not a duplicate question, I am trying to identify why i get a null reference exception whilst using an if statement to rule out the null object. If i have an "if" statement which handles the null why am i still evaluating the code inside?