NullReferenceException with Complex object in Tempdata collection

Viewed 19

The line where i try to get the message from the code-behind. Cause an error NullReferenceException, "object reference not set to an instance of an object". I tried to ignore that if it was null but nothing...

index.cshtml(landing page)

@page
@model IndexModel
@using WebAppProject.Models;
@using WebAppProject.Helpers;
@{
    // The error here is : object reference not set to an instance of an object
    string? msg = TempData.Get<FlashViewModel>("Data").Message ?? null;
}

<div>
    <h1 class="display-4">Welcome</h1>
    <p>Learn about <a href="https://docs.microsoft.com/aspnet/core">building Web apps with ASP.NET Core</a>.</p>
    @if(!string.IsNullOrEmpty(msg)){
        @msg
    }
</div>

index.cshtml.cs(code behind)

public void OnGet(){
       /* FlashViewModel flashMsg = new FlashViewModel { FlashEnum = FlashEnum.Success, Message = "Success!!!" };
       TempData.Put("Data", flashMsg); */
}
public class FlashViewModel
    {
        public string? Message { get; set; } = string.Empty;
        public FlashEnum FlashEnum { get; set; } = FlashEnum.Default;
        // FlashEnum : Danger, Success, Default, Info ecc.
    }
0 Answers
Related