Why am I getting a null reference exception for ASP.NET Core 3.1 empty view models?

RuNa 1 Reputation point
2022-09-18T18:56:44.567+00:00

Model Binding Null exception a View Component in Razor Pages
Framework : ASP.Net Core 3.1
Razor page

1) AppView Page -> ApplicantsView.cshtml

[@](/users/na/?userId=bfdb5561-671a-4323-ae78-921199b2092f)  
[@](/users/na/?userId=0f55de7e-bffd-0003-0000-000000000000) Mgmt101_Admin.Pages.ApplicantsViewModel  
@{  
    ViewData["Title"] = "Applicant View";  
}  
<div class="col-lg-6 col-sm-6">  
<div class="form-group">  
<p class="form-p-srb-p">[@](/users/na/?userId=0f55de7e-bffd-0003-0000-000000000000).Applicant.Id</p>  
<p class="form-p-srb-p">[@](/users/na/?userId=0f55de7e-bffd-0003-0000-000000000000).Applicant.Name</p>    
<p class="form-p-srb-p">[@](/users/na/?userId=0f55de7e-bffd-0003-0000-000000000000).Applicant.HouseNo</p>  --> error occurs "NullReferenceException: Object reference not set to an instance of an object"  
</div>  
</div>  

2) AppView Page -> ApplicantsView.cshtml.cs

using Microsoft.AspNetCore.Mvc;  
using System.Threading.Tasks;  
using Mgmt101_Admin.Models;  
using Mgmt101_Admin.Services;  
using System;  
using System.Collections.Generic;  
using System.Linq;  

namespace Mgmt101_Admin.Pages  
{  
     public class ApplicantsViewModel : BasePageModel  
    {  
         public ApplicantsViewModel(IBasePageService basePage, IApplicantService applicantsService)  
        {  
           try  
            {  
                _applicantsService = applicantsService;  
                 _basePage = basePage;  
             }  
             catch (Exception ex)  
             {  
                 TempData["ErrorMessage"] = ex.Message;  
             }  
         }  

        private readonly IApplicantService _applicantsService;  
        private readonly IBasePageService _basePage;  

        [BindProperty]  
         public ApplicantModel Applicant { get; set; }   
         public async Task LoadDataAsync(string id)  
        {  
             Applicant = await _applicantsService.GetApplicantDetailsAsync(id); // Wep API - Load Data from service  
        }  

        public async Task<IActionResult> OnGetAsync(string id)  
         {  
            try  
             {  
                await LoadDataAsync(id);  
             }  
             catch (Exception ex)  
             {  
                TempData["ErrorMessage"] = ex.Message;  
             }  
             return Page();  
         }  
   }  
 }  

3) Applicant Model class -> ApplicantModel.cs

 using System.Collections.Generic;  

 namespace Mgmt101_Admin.Models  
 {  
     public class ApplicantModel  
     {  
         public int Id { get; set; }  
         public string Name { get; set; }  
         public string HouseNo { get; set; }  
     }  
 }  

4) Interface class -> IApplicantService.cs

using Mgmt101_Admin.Models;  
 using System.Collections.Generic;  
 using System.Threading.Tasks;  

 namespace Mgmt101_Admin.Services  
 {  
     public interface IApplicantService  
     {  
         Task<ApplicantModel> GetApplicantDetailsAsync(string Id);  
     }  
 }  

5) Service Page -> ApplicantService.cs

namespace Mgmt101_Admin.Services  
 {  
     public class ApplicantService: IApplicantService  
     {  
         public async Task<ApplicantModel> GetApplicantDetailsAsync(string Id)  
         {  
             HttpResponseMessage message = await httpClient.GetAsync($"{URLPath}/{Id}");  
             string result = await message.Content.ReadAsStringAsync();  
             APIResponseModel response = JsonConvert.DeserializeObject<APIResponseModel>(result);  
             if (!response.Succeed) throw new System.Exception($"Errors occured. {GetErrorMessage(response)}");   
             if (response.Data == null) return null;  
             ApplicantModel applicant = JsonConvert.DeserializeObject<ApplicantModel>(response.Data.ToString());  
            return applicant;  
         }  
   }  
 }  

6) Data ->

 {"succeed":true,"message":null,"errors":null,"data":  
 [  
   {"id":"1234","name":"david","houseNo":null}  
 ],  

Because houseNo is null in this case, the value from the database is not retrun a value (null).
When binding the model (@默 .Applicant.HouseNo) in the view page, a NullReferenceException occurs.
How to resolve "NullReferenceException: Object reference not set to an instance of an object" when data is "null"

ASP.NET Core
ASP.NET Core
A set of technologies in the .NET Framework for building web applications and XML web services.
4,510 questions
{count} votes

Your answer

Answers can be marked as Accepted Answers by the question author, which helps users to know the answer solved the author's problem.