Click here to Skip to main content
15,897,704 members
Please Sign up or sign in to vote.
0.00/5 (No votes)
I am getting null reference exception for the following code in the view.


@if (Model.OperatorNotes.ApprovedBy.HasValue)  // null reference exception
{
<div class="row form-group">
<div class="col-xs-2 col-md-2 col-s-2">
Approved By
</div>
<div class="col-xs-10 col-md-10 col-s-10">
@UserHelper.GetUsername(Model.OperatorNotes.ApprovedBy.Value)
</div>
</div>
}


when there are records in the table 'OperatorNotes' no exception is raised.
How should i resolve this? what should i be using instead of '@if (Model.OperatorNotes.ApprovedBy.HasValue)'
Posted
Comments
Richard MacCutchan 7-Jan-16 6:15am    
You first need to check if any records exist.
John C Rayan 7-Jan-16 7:32am    
You could use
@if (Model.OperatorNotes.Count() > 0 && Model.OperatorNotes.ApprovedBy.HasValue).
But can you show us your model structure for OperatorNotes ? It doesn't look right to me.
sunnykvinod 7-Jan-16 7:38am    
public class OperatorNotesDto
{
public long OperatorNotesId { get; set; }

public string StatusSID { get; set; }

public DateTime NotificationDate { get; set; }

public Guid? ApprovedBy { get; set; }

public DateTime? ApprovedDate { get; set; }

public bool HasNotified { get; set; }

public DateTime? ProcessedDate { get; set; }

public int Archived { get; set; }

public int Deleted { get; set; }
}
sunnykvinod 7-Jan-16 7:40am    
i cant use Count method
John C Rayan 7-Jan-16 7:43am    
You have to initialize empty collection if no records in DB. That's the way you have to work in View.

1 solution

Try testing the OperatorNotes property for null before trying to access one of its properties:
C#
@if (Model.OperatorNotes != null && Model.OperatorNotes.ApprovedBy.HasValue)

Alternatively, if you're using C# 6, you could use the Null-conditional operator[^]:
C#
@if (Model.OperatorNotes?.ApprovedBy.HasValue)

(Note the extra ? in the property access: OperatorNotes?.ApprovedBy)
 
Share this answer
 

This content, along with any associated source code and files, is licensed under The Code Project Open License (CPOL)



CodeProject, 20 Bay Street, 11th Floor Toronto, Ontario, Canada M5J 2N8 +1 (416) 849-8900