I am building an invoice app that has basic CRUD functionality. Whenever I am trying to change the status of an invoice and redirect the user back to ViewInvoice page, I get a NullReferenceException for property Status of an Invoice object. What could be the reason for that ?
Here’s my Invoice model:
public class Invoice
{
public string InvoiceID { get; set; } = GenerateID.GenerateInvoiceID();
public string Description { get; set; }
public List<InvoiceItem> Items { get; set; }
public DateTime InvoiceDate { get; set; }
public string PaymentTerms { get; set; }
public DateTime PaymentDue { get; set; }
public int TotalPrice { get; set; }
public string Status { get; set; } = "pending";
public Client Client { get; set; }
}
Here’s the reference to the status property and the form in the ViewInvoice View page that triggers the request by calling OnPostPaid handler in ViewInvoice PageModel:
<p class="status-value">@Model.Invoice.Status</p>
<form asp-page-handler="paid" method="post">
<button class="mark-paid-link invoice-control-link">Mark as Paid</button>
</form>
Here’s ViewInvoice PageModel:
public Invoice Invoice { get; set; }
public readonly InvoiceContext _context;
public readonly InvoiceService _service;
public ViewInvoiceModel(InvoiceContext context, InvoiceService service)
{
_context = context;
_service = service;
}
public IActionResult OnGet(string id)
{
Invoice = IndexModel.invoices.Find(invoice => invoice.InvoiceID == id);
if(Invoice is null)
{
return NotFound();
}
return Page();
}
public IActionResult OnPostDelete(string id)
{
IndexModel.invoices.Remove(IndexModel.invoices.Find(item => item.InvoiceID == id));
return RedirectToPage("/index");
}
public void OnPostPaid(string id)
{
Invoice invoice = IndexModel.invoices.Find(invoice => invoice.InvoiceID == id);
if(invoice != null)
{
invoice.Status = "Paid";
}
}