问题
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]
public int Attempts { get; set; }
And inside the OnPost
I am doing this:
public IActionResult OnPost()
{
if(!IsCorrect())
{
Attempts++;
return Page();
}
return RedirectToPage($"./Index")
}
I expected this to update the data on the client side, since without [BindProperty]
& return Page()
, data would be lost if the model was invalid. However, Attempts
never increases on the client.
I think I may have misunderstood how this works? Any suggestions?
回答1:
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.
来源:https://stackoverflow.com/questions/53669863/change-bound-property-in-onpost-in-model-is-invalid