2

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)
3
  • Post the full exception text, including the call stack. Not just the message. The exception is probably thrown at a different location Commented May 8 at 14:48
  • Done. Stack trace added to the post. Commented May 8 at 15:01
  • 1
    There's no ModelForPartialView property or field in the page. var ModelForPartialView defines 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 the Model property using reflection. And there's no ModelForPartialView on the page. Instead of trying to hard-code data in the view, create a property in your IndexModel with the Airplane data and use for='Airplane' Commented May 8 at 15:22

1 Answer 1

1

The solution is to remove the page directive in the partial view, and to move the model class definition to outside of the Pages/Shared folder.

In a Razor Pages project, when you want to create a Partial View, do not create it as a new Razor Page. Instead, create a new Razor View (ie: Razor View – Empty). Doing it this way ensures there is no @page on the cshtml page, and that there is no C# code behind (ie: .cshtml.cs).

Pages/Shared/_Airplane.cshtml

@model Stackoverflow1.Models.Airplane

<p>The name of the pilot is:</p>

@if (Model != null) {
    @if (Model.PilotName != null) {
        @if (Model.PilotName.Length > 0) {
            <h4>@Model.PilotName</h4>
        }
    }
}

In your Models folder, create a new class. You could use a different name, but for this example, stick with “Airplane”.

Models/Airplane.cs

namespace Stackoverflow1.Models;

public class Airplane {
    public string PilotName { get; set; } = "";
}

On the page where you want to use the Partial View, be sure to create a new instance of the Airplane record.

Pages/Index.cshtml

@page
@using Stackoverflow1.Models
@model IndexModel
@{
    ViewData["Title"] = "Home page";
    var ModelForPartialView = new Airplane {
        PilotName = "Amelia Earhart"
    };
}

<h1>Welcome</h1>

<p>This is an example project.</p>

<partial name="_Airplane" model=ModelForPartialView />
Sign up to request clarification or add additional context in comments.

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.