I don't understand on how to fix the error, upon doing research on the error, it says that the error is caused when the property isn't declared in the class page. i then added declartation there and it still gives me the same error. below are the code snippets that might be related to the problem.
Severity Code Description Project File Line Suppression State Error (active) CS0120 An object reference is required for the non-static field, method, or property 'Model_Purchases.Details' Create.cshtml 175
create.cshtml
@foreach (var detail in Model_Purchases.Details){ <--- error is in this line here
<tr>
<td>
<div class="form-group">
<input asp-for="@detail.Product" class="form-control" />
<span asp-validation-for="@detail.Product" class="text-danger"></span>
</div>
</td>
<td>
<div class="form-group">
<input asp-for="@detail.Description" class="form-control" />
<span asp-validation-for="@detail.Description" class="text-danger"></span>
</div>
</td>
Model_Purchases.cs
namespace Accounting8.Data
{
public class Model_Purchases
{
//other properties here
public List<Model_PurchasesDetails> Details { get; set; }
public Model_Purchases()
{
Details = new List<Model_PurchasesDetails>();
}
}
}
create.cshtml.cs
create.cshtml.cs
using System;
using System.Collections.Generic;
using System.Linq;
using System.Threading.Tasks;
using Microsoft.AspNetCore.Mvc;
using Microsoft.AspNetCore.Mvc.RazorPages;
using Microsoft.AspNetCore.Mvc.Rendering;
using Accounting8.Data;
using Microsoft.EntityFrameworkCore;
namespace Accounting8.Pages.Purchases.Purchase_Requests
{
public class CreateModel : PageModel
{
private readonly Accounting8.Data.ApplicationDbContext _context;
public CreateModel(Accounting8.Data.ApplicationDbContext context)
{
_context = context;
Model_Purchases = new Model_Purchases();
Model_Purchases.Details = new List<Model_PurchasesDetails>();
}
public IActionResult OnGet()
{
return Page();
}
[BindProperty]
public Model_Purchases Model_Purchases { get; set; }
[BindProperty]
public Model_PurchasesDetails Model_PurchasesDetails { get; set; }
[BindProperty]
public List<Model_PurchasesDetails> Details { get; set; }
public async Task<IActionResult> OnPostAsync()
{
if (!ModelState.IsValid)
{
return Page();
}
// Add the purchase to the database
_context.PurchasesM.Add(Model_Purchases);
await _context.SaveChangesAsync();
// Loop through the purchase details and add them to the database
foreach (var detail in Model_Purchases.Details)
{
detail.TransactionNumber = Model_Purchases.TransactionNumber;
_context.PurchasesDetailsM.Add(detail);
}
await _context.SaveChangesAsync();
return RedirectToPage("./Index");
}
}
}