Reputation:
I am creating a simple todo application in Razor Pages with .NET Core 2.2:
public class IndexModel : PageModel
{
private readonly ApplicationDbContext _context;
public List<TodoItem> TodoItems { get; set; }
public IndexModel(ApplicationDbContext context)
{
_context = context;
}
public async Task OnGet()
{
TodoItems = await _context.TodoItems.Where(t => t.IsDone == false).ToListAsync();
}
but whenever I execute this code:
public async Task<IActionResult> OnPostMarkDoneAsync(int id)
{
if (!ModelState.IsValid)
{
return Page();
}
var item = TodoItems.First(t => t.Id == id);
item.IsDone = true;
_context.TodoItems.Update(item);
var ok = await _context.SaveChangesAsync();
if (ok != 1)
{
return BadRequest(500);
}
return RedirectToPage();
}
I always get a null exception. Also, even if it is in the same page.
When I start the application, the TodoItems list is populated with the correct data. But whenever I execute the OnPostMarkDoneAsync method and debug through it, it shows that the list is now null. Why is that?
Upvotes: 0
Views: 208
Reputation: 11
TodoItems will not be persisted across requests, so the fact that you have assigned to it in OnGet does not mean it will be still assigned to in OnPostMarkAsDoneAsync. You will need to refetch from the DbContext in OnPostMarkAsDoneAsync, as you have done in OnGet.
Upvotes: 1