gpt4 book ai didi

c# - 更改模型中 OnPost 中的绑定(bind)属性无效

转载 作者:太空宇宙 更新时间:2023-11-03 12:08:27 25 4
gpt4 key购买 nike

我正在使用 ASP.NET Core Razor Pages,我想为用户完成任务所需的尝试次数添加一个计数器。

我正在使用:

[BindProperty]
public int Attempts { get; set; }

OnPost 中我这样做:

public IActionResult OnPost()
{
if(!IsCorrect())
{
Attempts++;
return Page();
}

return RedirectToPage($"./Index")
}

我希望这会更新客户端的数据,因为如果没有 [BindProperty] & return Page(),如果模型无效,数据将会丢失。但是,Attempts 在客户端上永远不会增加。

我想我可能误解了它的工作原理?有什么建议吗?

最佳答案

一旦您的 OnPost 方法完成并呈现相应的 View ,使用 asp-for 标记帮助程序(或旧的 HtmlHelper 方法)从 ModelState 重新填充。这意味着即使您为 Attempts 设置了一个新值,它也不会被使用,因为 ModelState 中存在一个值和 Attempts键。

解决此问题的一种方法是清除存储在 ModelState 中的值,使用如下方法:

public IActionResult OnPost()
{
if (!IsCorrect())
{
ModelState.Remove(nameof(Attempts));
Attempts++;
return Page();
}

return RedirectToPage("./Index");
}

ModelState 值不存在时,将按预期从 PageModel 实现的 Attempts 属性中读取该值。

关于c# - 更改模型中 OnPost 中的绑定(bind)属性无效,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/53669863/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com