发布时如何清除Razor Page模型上的绑定属性? [英] How can you clear a bound property on a Razor Page's model when POSTing?

查看:93
本文介绍了发布时如何清除Razor Page模型上的绑定属性?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我有一个绑定到输入字段的属性:

I have a property that is bound to an input field:

<input id="name" asp-for="ContactName" name="ContactName" placeholder="Name" type="text" style="width: 200px !important;" autofocus>

[BindProperty]
public string ContactName { get; set; }

POST时,我尝试通过将 ContactName 属性设置为NULL或string.Empty来清除它,但是它不起作用.

When I POST, I tried clearing the ContactName property by setting it to NULL or string.Empty, but it doesn't work.

清除此字段的正确方法是什么?

What's the proper way to clear out this field?

推荐答案

正确"的方法是遵循PRG(后重定向获取)模式.输入的值来自 ModelState ,而不是 Model . ModelState 本身由 Request ViewData / ViewBag finally 的值组成em>模型.换句话说,如果在 Request 之类的对象中存在绑定成员的值,则该值将优先于您在模型上设置的任何值.

The "proper" way is to follow the PRG (Post-Redirect-Get) pattern. The values of your inputs come from ModelState, not Model. ModelState, itself, is composed of values from Request, ViewData/ViewBag, and finally model. In other words, if a value exists for a bound member in something like Request, that value will take precedence over anything you set on your model.

PRG模式指示您仅在出现验证错误时才应将视图返回给用户.在这种情况下,您希望要显示的已发布数据,而不是模型上的数据,以便用户可以纠正任何错误.如果用户输入有效,那么即使您返回到同一页面,您也将进行重定向.重定向操作清除了帖子中的所有内容.就像您是第一次访问该页面一样,因为实际上,这是一个全新的GET请求.

The PRG pattern instructs that you should only return the view back to the user when there is a validation error. In such cases, you want the posted data to be displayed rather than the data on the model, so that the user can correct any mistakes. If the user's input is valid, you redirect, even if it's back to the same page. The act of redirecting clears out everything from the post. It's like you're coming to the page for the first time, because in fact, it's an entirely new GET request.

这篇关于发布时如何清除Razor Page模型上的绑定属性?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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