How can you clear a bound property on a Razor Page's model when POSTing?

好久不见. 提交于 2019-12-13 19:18:36

问题


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; }

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?


回答1:


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.

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.



来源:https://stackoverflow.com/questions/52058441/how-can-you-clear-a-bound-property-on-a-razor-pages-model-when-posting

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!