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

Viewed 4405

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?

2 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.

There may be valid reasons for not wanting to follow the PRG pattern. For instance, you may be using a library like HTMX where you want deal with the post data and then return a Partial as the response directly from the OnPost method. The following is an approach that has worked for me. After modifying the Model values, call ModelState.Clear(), which will clear any errors in the Model and force the Model to be "rebuilt" with the new values. Then return your Page() or, in the following example, your Partial

public IActionResult OnPost()
{
    // process your post data...
    ContactName = String.Empty;
    ModelState.Clear();
    return Partial("_MyPartialView",this);
}
Related