Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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

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?

like image 817
ernest Avatar asked Aug 28 '18 12:08

ernest


1 Answers

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.

like image 159
Chris Pratt Avatar answered Sep 20 '22 18:09

Chris Pratt