模型中 OnPost 中的更改绑定属性无效 [英] Change Bound Property in OnPost in model is invalid

查看:26
本文介绍了模型中 OnPost 中的更改绑定属性无效的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我正在使用 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 方法完成并呈现相应的视图,使用 asp 的控件中显示的值-for Tag Helper(或旧的 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屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆