System.NullReferenceException: 'Object reference not set to an instance of an object.'

Aleem Ahmed 1 Reputation point
2022-01-27T10:43:42.157+00:00

168994-image1.png169033-image2.png

Not able to display Movie Name in View

.NET
.NET
Microsoft Technologies based on the .NET software framework.
3,459 questions
ASP.NET Core
ASP.NET Core
A set of technologies in the .NET Framework for building web applications and XML web services.
4,240 questions
{count} votes

1 answer

Sort by: Most helpful
  1. Zhi Lv - MSFT 32,046 Reputation points Microsoft Vendor
    2022-01-28T03:08:04.153+00:00

    Hi @Aleem Ahmed ,

    You can refer the following screenshot, since in the HttpGet method, we didn't create a Movie instance to the returned model, in the view page, when we display the movie name it will show the null reference exception.

    169158-image.png

    You can check your HttpGet method, make sure the return data contains the Movie value.

    Besides, you can also check the Movie is null when display the Movie. Add a ? at the end of the Movie, code like this:

        @foreach (var item in Model.ShoppingCart.ShoppingCartItems) {  
                <tr>  
                    <td>  
                        @Html.DisplayFor(modelItem => item.Id)  
                    </td>  
                    <td>  
                        @Html.DisplayFor(modelItem => item.Amount)  
                    </td>  
                    <td>  
                        @item.Movie?.MovieName  
                    </td>  
                    <td>  
                        @Html.DisplayFor(modelItem => item.ShoppingCartId)  
                    </td>  
                    <td>  
                        @Html.ActionLink("Edit", "Edit", new { /* id=item.PrimaryKey */ }) |  
                        @Html.ActionLink("Details", "Details", new { /* id=item.PrimaryKey */ }) |  
                        @Html.ActionLink("Delete", "Delete", new { /* id=item.PrimaryKey */ })  
                    </td>  
                </tr>  
        }  
    

    In this scenario, when the Movie is null, it will not throw the Null reference exception, the result like this:

    169267-image.png


    If the answer is the right solution, please click "Accept Answer" and kindly upvote it. If you have extra questions about this answer, please click "Comment".
    Note: Please follow the steps in our documentation to enable e-mail notifications if you want to receive the related email notification for this thread.

    Best regards,
    Dillion

    0 comments No comments