I have a situation where I am getting a NullReferenceException when I am checking a model (not a property) to see if it is null. Follow these steps to re-create the issue yourself.
Create a brand new ASP.NET Core 8 web app (Razor Pages) using C#. In the Pages/Shared folder, create a new Razor page called Airplane (ie: _Airplane) and add a property called PilotName. This will be our partial view.
_Airplane.cshtml.cs:
using Microsoft.AspNetCore.Mvc.RazorPages;
namespace Stackoverflow1.Pages.Shared
{
public class _AirplaneModel : PageModel
{
public string PilotName { get; set; } = "";
public void OnGet()
{
}
}
}
On the Index page (ie: Pages/Index.cshtml), create a new instance of the Airplane model and populate it with a value, and then add the partial view to the page.
Index.cshtml:
@page
@model IndexModel
@{
ViewData["Title"] = "Home page";
var ModelForPartialView = new Stackoverflow1.Pages.Shared._AirplaneModel
{
PilotName = "Amelia Earhart"
};
}
<h1>Welcome</h1>
<p>This is an example project.</p>
<partial name="_Airplane" model="ModelForPartialView" />
If you run the project now, it works!
To see the null exception, go to the _Airplane.cshtml page and add code to check if the model is null. In the example below, I have added additional checks for your reference – just uncomment them as needed.
_Airplane.cshtml:
@page
@model Stackoverflow1.Pages.Shared._AirplaneModel
@{
}
<p>The name of the pilot is:</p>
@if (Model != null)
{
@* @if (Model.PilotName != null)
{
@if (Model.PilotName.Length > 0)
{
<h4>@Model.PilotName</h4>
}
} *@
}
Now when you run the project, it throws a NullReferenceException when checking if the model is null on line 8.
@if (Model != null)
This is the error:
System.NullReferenceException: Object reference not set to an instance of an object.
Looking at this basic example, can you explain why I get a null reference exception when checking if an object is null?
If my technique is wrong, please tell me. So far, everything seems to be correct, and I have had 2 other people check my work and none of us can figure this out. This error seems to defy all logic.
The complete stack trace is below.
System.NullReferenceException: Object reference not set to an instance of an object.
at Stackoverflow1.Pages.Shared.Pages_Shared__Airplane.get_Model()
at Stackoverflow1.Pages.Shared.Pages_Shared__Airplane.ExecuteAsync() in C:\SourceCode\Web\WebCode\ASP.NET Core\C#\HowTo\RazorPages\Stackoverflow1\Stackoverflow1\Pages\Shared\_Airplane.cshtml:line 8
at Microsoft.AspNetCore.Mvc.Razor.RazorView.RenderPageCoreAsync(IRazorPage page, ViewContext context)
at Microsoft.AspNetCore.Mvc.Razor.RazorView.RenderPageAsync(IRazorPage page, ViewContext context, Boolean invokeViewStarts)
at Microsoft.AspNetCore.Mvc.Razor.RazorView.RenderAsync(ViewContext context)
at Microsoft.AspNetCore.Mvc.TagHelpers.PartialTagHelper.RenderPartialViewAsync(TextWriter writer, Object model, IView view)
at Microsoft.AspNetCore.Mvc.TagHelpers.PartialTagHelper.ProcessAsync(TagHelperContext context, TagHelperOutput output)
at Microsoft.AspNetCore.Razor.Runtime.TagHelpers.TagHelperRunner.<RunAsync>g__Awaited|0_0(Task task, TagHelperExecutionContext executionContext, Int32 i, Int32 count)
at Stackoverflow1.Pages.Pages_Index.ExecuteAsync() in C:\SourceCode\Web\WebCode\ASP.NET Core\C#\HowTo\RazorPages\Stackoverflow1\Stackoverflow1\Pages\Index.cshtml:line 5
at Microsoft.AspNetCore.Mvc.Razor.RazorView.RenderPageCoreAsync(IRazorPage page, ViewContext context)
at Microsoft.AspNetCore.Mvc.Razor.RazorView.RenderPageAsync(IRazorPage page, ViewContext context, Boolean invokeViewStarts)
at Microsoft.AspNetCore.Mvc.Razor.RazorView.RenderAsync(ViewContext context)
at Microsoft.AspNetCore.Mvc.ViewFeatures.ViewExecutor.ExecuteAsync(ViewContext viewContext, String contentType, Nullable`1 statusCode)
at Microsoft.AspNetCore.Mvc.ViewFeatures.ViewExecutor.ExecuteAsync(ViewContext viewContext, String contentType, Nullable`1 statusCode)
at Microsoft.AspNetCore.Mvc.Infrastructure.ResourceInvoker.<InvokeNextResultFilterAsync>g__Awaited|30_0[TFilter,TFilterAsync](ResourceInvoker invoker, Task lastTask, State next, Scope scope, Object state, Boolean isCompleted)
at Microsoft.AspNetCore.Mvc.Infrastructure.ResourceInvoker.Rethrow(ResultExecutedContextSealed context)
at Microsoft.AspNetCore.Mvc.Infrastructure.ResourceInvoker.ResultNext[TFilter,TFilterAsync](State& next, Scope& scope, Object& state, Boolean& isCompleted)
at Microsoft.AspNetCore.Mvc.Infrastructure.ResourceInvoker.InvokeResultFilters()
--- End of stack trace from previous location ---
at Microsoft.AspNetCore.Mvc.Infrastructure.ResourceInvoker.<InvokeNextResourceFilter>g__Awaited|25_0(ResourceInvoker invoker, Task lastTask, State next, Scope scope, Object state, Boolean isCompleted)
at Microsoft.AspNetCore.Mvc.Infrastructure.ResourceInvoker.Rethrow(ResourceExecutedContextSealed context)
at Microsoft.AspNetCore.Mvc.Infrastructure.ResourceInvoker.Next(State& next, Scope& scope, Object& state, Boolean& isCompleted)
at Microsoft.AspNetCore.Mvc.Infrastructure.ResourceInvoker.InvokeFilterPipelineAsync()
--- End of stack trace from previous location ---
at Microsoft.AspNetCore.Mvc.Infrastructure.ResourceInvoker.<InvokeAsync>g__Awaited|17_0(ResourceInvoker invoker, Task task, IDisposable scope)
at Microsoft.AspNetCore.Mvc.Infrastructure.ResourceInvoker.<InvokeAsync>g__Awaited|17_0(ResourceInvoker invoker, Task task, IDisposable scope)
at Microsoft.AspNetCore.Authorization.AuthorizationMiddleware.Invoke(HttpContext context)
at Microsoft.AspNetCore.Authentication.AuthenticationMiddleware.Invoke(HttpContext context)
at Microsoft.AspNetCore.Diagnostics.DeveloperExceptionPageMiddlewareImpl.Invoke(HttpContext context)
ModelForPartialViewproperty or field in the page.var ModelForPartialViewdefines a variable that's only visible in its code block. The stack trace shows the exception is thrown when the partial page starts rendering and tries to retrieve the data that's returned by theModelproperty using reflection. And there's noModelForPartialViewon the page. Instead of trying to hard-code data in the view, create a property in yourIndexModelwith the Airplane data and usefor='Airplane'