0

I am trying to make a simple query which will search through my entity database and display all the reports and display all the reports with name "Fintan" . I am able to get the program to display all the the db but when I enter @if (line.name.Contains("Fintan")==true) I get a nullReferenceException. Even tho there are reports with name= "Fintan"

View

@model DisplayViewModels
 @foreach (var line in Model.Reports)
    { 
       @if (line.name.Contains("Fintan")==true)
        {
            <h1>@line.name</h1>
        }
    }

Controller

 public IActionResult SearchResults()
    {
            var displayViewModel = new DisplayViewModel
        {
                Reports = _reportRepository.AllReports
            };
        return View(displayViewModel); }
    }
  • Even though there are instances where there is a match there is at least one instance where either `line` or `line.name` is `null` and that will result in an NRE being thrown. Read the answer in the duplicate to get a better understanding of how you can troubleshoot NREs in the future. – Igor Feb 28 '20 at 20:59
  • In the meantime, changing `@if (line.name.Contains("Fintan")==true)` to `@if (line?.name?.Contains("Fintan")==true)` should fix your issue – TheBatman Feb 28 '20 at 21:19
  • Anytime you get a `NullReferenceException` and you conclude "this doesn't make sense! its not null!" look again, because the computer isn't wrong. –  Feb 28 '20 at 21:33

0 Answers0