Marius Vasile

Marius Vasile

  • 588
  • 1.7k
  • 124.5k

ASP.NET Core Razor Add new data from Main page

May 24 2020 5:54 AM
I am trying to add new data and on "Save" to automatically refresh data. However, on save I get error 
 
System.NullReferenceException: 'Object reference not set to an instance of an object.'
RoSafety.Pages.PTW.IsoC.IsoCertModel.ICData.get returned null.
 If I use a separate page for Post, the data is saved but on same page as OnGet is not. How should I do it?
  
  1. [BindProperty]  
  2.         public ICContent ICContent { getset; }  
  3.         public ICData ICData { getset; }  
  4.   
  5.         public async Task<IActionResult> OnGetAsync()  
  6.         {  
  7.             ICData = await _context.ICDatas  
  8.                 .Include(a=>a.ICContents)  
  9.                 .AsNoTracking()  
  10.                 .FirstOrDefaultAsync(a => a.IdICD == 1);  
  11.   
  12.             if (ICData == null)  
  13.             {  
  14.                 return NotFound();  
  15.             }  
  16.             return Page();  
  17.         }  
  18.   
  19.         public async Task<IActionResult> OnPostAsync()  
  20.         {  
  21.             if (!ModelState.IsValid)  
  22.             {  
  23.                 return Page();  
  24.             }  
  25.   
  26.             var emptyIsoCert = new ICContent();  
  27.   
  28.             if (await TryUpdateModelAsync(emptyIsoCert, "ICContent",  
  29.                   
  30.                 s => s.Equipment,  
  31.                 s => s.EnergSource,  
  32.                 s => s.IsoType,  
  33.                 s => s.IsoMethod,  
  34.                 s => s.LockNo,  
  35.                 s => s.PreparedBy,  
  36.                 s => s.ImplementedBy,  
  37.                 s => s.VerifiedBy,  
  38.                 s => s.IsoStatus ))  
  39.   
  40.             {  
  41.                 _context.ICContents.Add(emptyIsoCert);  
  42.                 await _context.SaveChangesAsync();  
  43.                 //return RedirectToPage("IsoCert");  
  44.                 return await OnGetAsync();  
  45.             }  
  46.   
  47.             return null;  
  48.         }  
 

Answers (7)