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?
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.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With