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

查看:71
本文介绍了在模型中的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方法完成并呈现了相应的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屋!

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