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

Brent Humber 21 Reputation points
2021-03-15T21:21:48.937+00:00

This error got me, I'm using code first: System.NullReferenceException: 'Object reference not set to an instance of an object.' el IEnumerable<BrentStat5.Context.CorvetteCost> @{ ViewData["Title"] = "Index"; } <h1>Index</h1> <p> <a asp-action="Create">Create New</a> </p> <table class="table"> <thead> <tr> <th> @azzedinehtmlsql .DisplayNameFor(model => model.CorvetteItem) </th> <th> @azzedinehtmlsql .DisplayNameFor(model => model.CorvetteItemCost) </th> <th> @azzedinehtmlsql .DisplayNameFor(model => model.CorvetteStore) </th> <th> @azzedinehtmlsql .DisplayNameFor(model => model.Repair) </th> <th> @azzedinehtmlsql .DisplayNameFor(model => model.Upgrade) </th> <th> @azzedinehtmlsql .DisplayNameFor(model => model.Date) </th> <th> @azzedinehtmlsql .DisplayNameFor(model => model.Maintance) </th> <th> @azzedinehtmlsql .DisplayNameFor(model => model.OrginalCost) </th> <th></th> </tr> </thead> <tbody> @foreach (var item in Model) { //error is on this line. <tr> <td> @azzedinehtmlsql .DisplayFor(modelItem => item.CorvetteItem) </td> <td> @azzedinehtmlsql .DisplayFor(modelItem => item.CorvetteItemCost) </td> <td> @azzedinehtmlsql .DisplayFor(modelItem => item.CorvetteStore) </td> <td> @azzedinehtmlsql .DisplayFor(modelItem => item.Repair) </td> <td> @azzedinehtmlsql .DisplayFor(modelItem => item.Upgrade) </td> <td> @azzedinehtmlsql .DisplayFor(modelItem => item.Date) </td> <td> @azzedinehtmlsql .DisplayFor(modelItem => item.Maintance) </td> <td> @azzedinehtmlsql .DisplayFor(modelItem => item.OrginalCost) </td> <td> <a asp-action="Edit" asp-route-id="@item.CorvetteId">Edit</a> | <a asp-action="Details" asp-route-id="@item.CorvetteId">Details</a> | <a asp-action="Delete" asp-route-id="@item.CorvetteId">Delete</a> </td> </tr> } </tbody> </table>

.NET Runtime
.NET Runtime
.NET: Microsoft Technologies based on the .NET software framework.Runtime: An environment required to run apps that aren't compiled to machine language.
1,125 questions
{count} votes

Accepted answer
  1. Jerry Cai-MSFT 986 Reputation points
    2021-03-16T05:41:29.44+00:00

    Hi,BrentHumber

    This error often means model can't get the value from controller, you should pass the value to view:

    public IActionResult Index()
            {
                var model= new List<MyModel>()
                {
                    new MyModel{ CorvetteId=1,CorvetteItem="aa"},
                    new MyModel{ CorvetteId=2,CorvetteItem="bb"}
                };
                return View(model);
            }
    

    Best Regards,
    Jerry Cai


    If the answer is helpful, please click "Accept Answer" and upvote it.
    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.

    0 comments No comments

0 additional answers

Sort by: Most helpful