Change Bound Property in OnPost in model is invalid

余生颓废 提交于 2020-01-02 10:31:40

问题


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

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!