NullReferenceException when runningView

chairmanPC

Active member
Joined
Apr 19, 2021
Messages
38
Programming Experience
10+
I have followed this site on creating a MVC ASP.NET: Create a View in ASP.NET MVC. I am new to this, so I'm familiarising myself with ASP.NET.

The first few tutorials were smooth, until I created the view page.

Model:
using System;
using System.Collections.Generic;
using System.Linq;
using System.Web;

namespace simpleAPI.Models
{
    public class Staff
    {
        public string staffName { get; set; }
        public string staffOccupation { get; set; }
        public int staffAge { get; set; }
    }
}

Control:
using simpleAPI.Models;
using System;
using System.Collections.Generic;
using System.Linq;
using System.Web;
using System.Web.Mvc;

namespace simpleAPI.Controllers
{

    public class staffController : Controller
    {

        static IList<Staff> staffList = new List<Staff>{
                new Staff() { staffName = "John", staffOccupation = "Doctor", staffAge = 18 } ,
                new Staff() { staffName = "Steve", staffOccupation = "Doctor", staffAge = 21 } ,
                new Staff() { staffName = "Bill",  staffOccupation = "Doctor",staffAge = 25 } ,
                new Staff() { staffName = "Ram" , staffOccupation = "Doctor", staffAge = 20 } ,
                new Staff() { staffName = "Ron" , staffOccupation = "Doctor", staffAge = 31 } ,
                new Staff() { staffName = "Chris" , staffOccupation = "Doctor", staffAge = 17 } ,
                new Staff() { staffName = "Rob" , staffOccupation = "Doctor", staffAge = 19 }

            };
        // GET: busModel
        public ActionResult Index()
        {
            return View();
        }
    }
}
View:
@model IEnumerable<simpleAPI.Models.Staff>

@{
    ViewBag.Title = "Index";
    Layout = "~/Views/Shared/_Layout.cshtml";
}

<h2>Index</h2>

<p>
    @Html.ActionLink("Create New", "Create")
</p>
<table class="table">
    <tr>
        <th>
            @Html.DisplayNameFor(model => model.staffName)
        </th>
        <th>
            @Html.DisplayNameFor(model => model.staffOccupation)
        </th>
        <th>
            @Html.DisplayNameFor(model => model.staffAge)
        </th>
        <th></th>
    </tr>

@foreach (var item in Model) {
    <tr>
        <td>
            @Html.DisplayFor(modelItem => item.staffName)
        </td>
        <td>
            @Html.DisplayFor(modelItem => item.staffOccupation)
        </td>
        <td>
            @Html.DisplayFor(modelItem => item.staffAge)
        </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>
}

</table>

Last but not least, the routeConfig
RouteConfig:
using System;
using System.Collections.Generic;
using System.Linq;
using System.Web;
using System.Web.Mvc;
using System.Web.Routing;

namespace simpleAPI
{
    public class RouteConfig
    {
        public static void RegisterRoutes(RouteCollection routes)
        {
            routes.IgnoreRoute("{resource}.axd/{*pathInfo}");

            routes.MapRoute(
                name: "Default",
                url: "{controller}/{action}/{id}",
                defaults: new { controller = "staff", action = "Index", id = UrlParameter.Optional }
            );
        }
    }
}

URL: https://localhost:44397/staff/Index

And here, I got NullReferenceException when I test ran it. What did I miss?
 
Solution
I have found the solution.

It all began in the View().

C#:
   // GET: Bus
        public ActionResult Index()
        {
            return View();
        }

As many people were getting the same error as I am, the reason is because there was no argument in the View(), that's why the View did not have any lists to read, therefore the values were null.

I added a IList and assigned values like this:

Revised code:
        // GET: busModel
        public ActionResult Index()
        {
            return View(staffList);
        }
        }
Show us the complete callstack of the exception.

Where do you pass your model data to your view?
 
Show us the complete callstack of the exception.

Where do you pass your model data to your view?
I passed it from Staff.cs to Index.cshtml.

Call stacl:
     System.Web.Mvc.dll!System.Web.Mvc.ControllerActionInvoker.InvokeActionResultWithFilters(System.Web.Mvc.ControllerContext controllerContext, System.Collections.Generic.IList<System.Web.Mvc.IResultFilter> filters, System.Web.Mvc.ActionResult actionResult)    Unknown
     System.Web.Mvc.dll!System.Web.Mvc.Async.AsyncControllerActionInvoker.BeginInvokeAction.AnonymousMethod__4()    Unknown
     System.Web.Mvc.dll!System.Web.Mvc.Async.AsyncControllerActionInvoker.BeginInvokeAction.AnonymousMethod__1(System.IAsyncResult asyncResult)    Unknown
     System.Web.Mvc.dll!System.Web.Mvc.Async.AsyncResultWrapper.WrappedAsyncResult<bool>.CallEndDelegate(System.IAsyncResult asyncResult)    Unknown
     System.Web.Mvc.dll!System.Web.Mvc.Async.AsyncResultWrapper.WrappedAsyncResultBase<bool>.End()    Unknown
     System.Web.Mvc.dll!System.Web.Mvc.Async.AsyncControllerActionInvoker.EndInvokeAction(System.IAsyncResult asyncResult)    Unknown
     System.Web.Mvc.dll!System.Web.Mvc.Controller.BeginExecuteCore.AnonymousMethod__152_1(System.IAsyncResult asyncResult, System.Web.Mvc.Controller.ExecuteCoreState innerState)    Unknown
     System.Web.Mvc.dll!System.Web.Mvc.Async.AsyncResultWrapper.WrappedAsyncVoid<System.Web.Mvc.Controller.ExecuteCoreState>.CallEndDelegate(System.IAsyncResult asyncResult)    Unknown
     System.Web.Mvc.dll!System.Web.Mvc.Async.AsyncResultWrapper.WrappedAsyncResultBase<System.Web.Mvc.Async.AsyncVoid>.End()    Unknown
     System.Web.Mvc.dll!System.Web.Mvc.Controller.EndExecuteCore(System.IAsyncResult asyncResult)    Unknown
     System.Web.Mvc.dll!System.Web.Mvc.Controller.BeginExecute.AnonymousMethod__151_2(System.IAsyncResult asyncResult, System.Web.Mvc.Controller controller)    Unknown
     System.Web.Mvc.dll!System.Web.Mvc.Async.AsyncResultWrapper.WrappedAsyncVoid<System.__Canon>.CallEndDelegate(System.IAsyncResult asyncResult)    Unknown
     System.Web.Mvc.dll!System.Web.Mvc.Async.AsyncResultWrapper.WrappedAsyncResultBase<System.Web.Mvc.Async.AsyncVoid>.End()    Unknown
     System.Web.Mvc.dll!System.Web.Mvc.Controller.EndExecute(System.IAsyncResult asyncResult)    Unknown
     System.Web.Mvc.dll!System.Web.Mvc.Controller.System.Web.Mvc.Async.IAsyncController.EndExecute(System.IAsyncResult asyncResult)    Unknown
     System.Web.Mvc.dll!System.Web.Mvc.MvcHandler.BeginProcessRequest.AnonymousMethod__20_1(System.IAsyncResult asyncResult, System.Web.Mvc.MvcHandler.ProcessRequestState innerState)    Unknown
     System.Web.Mvc.dll!System.Web.Mvc.Async.AsyncResultWrapper.WrappedAsyncVoid<System.Web.Mvc.MvcHandler.ProcessRequestState>.CallEndDelegate(System.IAsyncResult asyncResult)    Unknown
     System.Web.Mvc.dll!System.Web.Mvc.Async.AsyncResultWrapper.WrappedAsyncResultBase<System.Web.Mvc.Async.AsyncVoid>.End()    Unknown
     System.Web.Mvc.dll!System.Web.Mvc.MvcHandler.EndProcessRequest(System.IAsyncResult asyncResult)    Unknown
     System.Web.Mvc.dll!System.Web.Mvc.MvcHandler.System.Web.IHttpAsyncHandler.EndProcessRequest(System.IAsyncResult result)    Unknown
     System.Web.dll!System.Web.HttpApplication.CallHandlerExecutionStep.System.Web.HttpApplication.IExecutionStep.Execute()    Unknown
     System.Web.dll!System.Web.HttpApplication.ExecuteStepImpl(System.Web.HttpApplication.IExecutionStep step)    Unknown
     System.Web.dll!System.Web.HttpApplication.ExecuteStep(System.Web.HttpApplication.IExecutionStep step, ref bool completedSynchronously)    Unknown
     System.Web.dll!System.Web.HttpApplication.PipelineStepManager.ResumeSteps(System.Exception error)    Unknown
     System.Web.dll!System.Web.HttpApplication.BeginProcessRequestNotification(System.Web.HttpContext context, System.AsyncCallback cb)    Unknown
     System.Web.dll!System.Web.HttpRuntime.ProcessRequestNotificationPrivate(System.Web.Hosting.IIS7WorkerRequest wr, System.Web.HttpContext context)    Unknown
     System.Web.dll!System.Web.Hosting.PipelineRuntime.ProcessRequestNotificationHelper(System.IntPtr rootedObjectsPointer, System.IntPtr nativeRequestContext, System.IntPtr moduleData, int flags)    Unknown
     System.Web.dll!System.Web.Hosting.PipelineRuntime.ProcessRequestNotification(System.IntPtr rootedObjectsPointer, System.IntPtr nativeRequestContext, System.IntPtr moduleData, int flags)    Unknown
     [Native to Managed Transition]   
     [Managed to Native Transition]   
     System.Web.dll!System.Web.Hosting.PipelineRuntime.ProcessRequestNotificationHelper(System.IntPtr rootedObjectsPointer, System.IntPtr nativeRequestContext, System.IntPtr moduleData, int flags)    Unknown
     System.Web.dll!System.Web.Hosting.PipelineRuntime.ProcessRequestNotification(System.IntPtr rootedObjectsPointer, System.IntPtr nativeRequestContext, System.IntPtr moduleData, int flags)    Unknown
 
Which line? I'm not seeing it.

See line 1.:
@foreach (var item in Model) { <<<---- THIS LINE. THIS LINE SPAT OUT THE EXCEPTION AT ME.
    <tr>
        <td>
            @Html.DisplayFor(modelItem => item.staffName)
        </td>
        <td>
            @Html.DisplayFor(modelItem => item.staffOccupation)
        </td>
        <td>
            @Html.DisplayFor(modelItem => item.staffAge)
        </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>
}
 
Last edited:
I have found the solution.

It all began in the View().

C#:
   // GET: Bus
        public ActionResult Index()
        {
            return View();
        }

As many people were getting the same error as I am, the reason is because there was no argument in the View(), that's why the View did not have any lists to read, therefore the values were null.

I added a IList and assigned values like this:

Revised code:
        // GET: busModel
        public ActionResult Index()
        {
            return View(staffList);
        }
        }
 
Solution
See. I told you that you weren't passing the model to the view in your Staff.cs.
 
Back
Top Bottom