I am using ASP.NET Core Razor Pages and I want to add a counter for a number of attempts it takes a user complete a task.
I am using:
[BindProperty]
Once your OnPost method completes and the corresponding View is rendered, the values that are displayed in controls that use the asp-for Tag Helper (or the older HtmlHelper methods) are repopulated from ModelState. This means that even though you are setting a new value for Attempts, it is simply not being used because a value exists in ModelState with the Attempts key.
One way to fix this is to clear the value that's stored in ModelState, using something like this:
public IActionResult OnPost()
{
if (!IsCorrect())
{
ModelState.Remove(nameof(Attempts));
Attempts++;
return Page();
}
return RedirectToPage("./Index");
}
When a ModelState value doesn't exist, the value is read from the Attempts property on your PageModel implementation, as expected.