在模型中的OnPost中更改绑定属性无效 [英] Change Bound Property in OnPost in model is invalid
问题描述
我正在使用ASP.NET Core Razor Pages,并且我想添加一个计数器来计算用户完成一项任务所需的尝试次数.
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.
我正在使用:
[BindProperty]
public int Attempts { get; set; }
在OnPost
内部,我正在这样做:
And inside the OnPost
I am doing this:
public IActionResult OnPost()
{
if(!IsCorrect())
{
Attempts++;
return Page();
}
return RedirectToPage($"./Index")
}
我希望这会更新客户端的数据,因为没有[BindProperty]
& return Page()
,如果模型无效,数据将丢失.但是,Attempts
永远不会在客户端上增加.
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?
推荐答案
一旦您的OnPost
方法完成并呈现了相应的View,使用asp-for
标记帮助器(或更旧的控件)的控件中显示的值HtmlHelper
方法)从ModelState
重新填充.这意味着即使您为Attempts
设置了新值,也不会使用它,因为使用Attempts
键在ModelState
中存在一个值.
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.
解决此问题的一种方法是使用类似以下的方法清除存储在ModelState
中的值:
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");
}
当ModelState
值不存在时,将按预期方式从PageModel
实现的Attempts
属性读取该值.
When a ModelState
value doesn't exist, the value is read from the Attempts
property on your PageModel
implementation, as expected.
这篇关于在模型中的OnPost中更改绑定属性无效的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!