Search code examples
htmlasp.net-mvcentity-frameworkview

How to avoid NullReferenceException while displaying all values in a table in MVC View?


I have a web project in which I use MVC and Entity Framework. I have a company and a plant table. Plant table is related to company via companyId foreign key. In my view I take plant's data from user via form (plantNo, plantName, plantDefinition). In my index page I take a company Id from user and create a a company for that Id, then redirect to company page where I take company fields data from the user (companyName, companyAddress etc,) and redirect to Plants page. In the plants page the each new plant is added and they all have the same companyId since they all belong to that company. Initially there are no plants when the user first enters the page so I get a NullReferenceException when I try to display all Plant entries in my Plant table. I wrote an else statement to display default values because I thought that if I check my model is null, and print default values, there would be no NullReferenceException errors.

What would be a reasonable way to implement table where all plants are displayed, and after a new plant is submitted, the table is updated also?

Here's my code snippet for the described problem:

<table class="table">
    <thead>
        <tr>
            <th style="width:120px;">Plant Number</th>
            <th>Plant Name</th>
            <th>Plant Definition</th>
            <th>Update</th>
            <th>Delete</th>
        </tr>
    </thead>
    <tbody>
        @if (Model.Company.Plants!= null)
        {
            @foreach (var item in Model.Company.Plants)
            {
                <th>@item.PlantNo</th>
                <td>@item.PlantName</td>
                <td>@item.PlantDefinition</td>
            }
        }
        else
        {
            <th>Plant Default Number</th>
            <td>Plant Default Name</td>
            <td>Plant Default Definition</td>

        }
    </tbody>
</table>

EDIT

As per the discussion in the comment section, it turns out that Model is null.


Solution

  • You are checking for

    Model.Company.Plants!= null
    

    which is checking whether the Plants of the Company of Model differs from null. However, since Model is null, Model.Company makes no sense. It's basically asking for the Company of an unknown/unexisting Model. You could change your conditional to something like:

    @if ((Model != null) && (Model.Company != null) && (Model.Company.Plants!= null))
    

    and then it should go and execute your else statement if any of them is null.