I am using Razor Pages with model binding. When my form posts, the values remain in there when the page reloads after posting. I have tried using ModelState.Clear() but this doesn't seem to do anything.
Specifically, I have an HTML form like this:
<form method="post">
<textarea asp-for="Input.Text" class="form-control" placeholder="No data"></textarea>
<button type="submit" asp-route-param="Submit">Submit</button>
</form>
and the following controller:
public class TestFormModel : PageModel
{
[BindProperty]
public InputModel Input { get; set; }
public IActionResult OnPost()
{
ModelState.Clear();
return Page();
}
}
public class InputModel
{
public string Text {get;set;}
}
On submission, the form remembers the text submitted - I want it to be cleared.
I can do this with jQuery on the client side, but I wondered if there's a RazorPages trick. ModelState.Clear() doesn't seem to do what I want.
Many thanks
I addition to clearing the model state you need to also clear the bound property. like this:
public IActionResult OnPost()
{
ModelState.Clear();
Input.Text = string.Empty;
return Page();
}
Because the bound model (in your case InputModel) may have several properties within it, clearing the properties one at a time may not be ideal.
The most suitable way to clear a form in this case would be:
public IActionResult OnPost()
{
/*
* Your logic...
*/
foreach (var entry in ModelState.Values)
{
entry.AttemptedValue = "";
entry.RawValue = "";
}
return Page();
}
Here, we clear the AttemptedValue
and RawValue
of all properties in the bound Model essentially resetting them after post returns the view.
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