Change Bound Property in OnPost in model is invalid

后端 未结 1 1651
一向
一向 2021-01-14 14:04

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]
         


        
相关标签:
1条回答
  • 2021-01-14 14:23

    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.

    0 讨论(0)
提交回复
热议问题