How to fully reset/clear ASP.NET Core MVC form using JavaScript?

Viewed 4642

I need to use JS (or jQuery) to reset a form. It works fine if fill out the fields and click Reset. The problem starts when I submit the form with at least one field having a model error. When the form with model errors is returned back and I click reset, the fields that did not have model errors do not reset.

What is happening here and how can I make all fields always reset, regardless of whether or not there were any model errors? Additionally, I would like to have the model errors disappear on reset too.

Gif below shows the field I highlight does not reset:

I want highlighted field to reset

HTML

@model SampleViewModel
@{
    ViewData["Title"] = "Home Page";
}


<script>
    function ResetFormWithJS() {
        document.getElementById('FormEyeDee').reset();
    }
</script>

<center>
    <form id="FormEyeDee"asp-action="Index" method="post">
        Name:
        <input asp-for="Name" />
        <span asp-validation-for="Name" class="text-danger"></span>
        <hr />
        Email:
        <input asp-for="Email" />
        <span asp-validation-for="Email" class="text-danger"></span>
        <hr />
        <input type="submit" value="Submit" />
        <input type="reset" onclick="ResetFormWithJS();" />
    </form>
    <br>
</center>

Controller:

public class HomeController : Controller
{
    [HttpGet]
    public IActionResult Index()
    {
        return View();
    }

    [HttpPost]
    public IActionResult Index(SampleViewModel Model)
    {
        if (!ModelState.IsValid)
        {
            return View("Index", Model);
        }

        return RedirectToAction("Index");
    }
}

Model

public class SampleViewModel
{
    [Required]
    public string Name { get; set; }
    [Required]
    public string Email { get; set; }
}
2 Answers

If you're looking for a pure JavaScript solution, try this:

function ResetFormWithJS() {
    document.querySelector("[asp-for='Name']").value = "";
    document.querySelector("[asp-for='Email']").value = "";
}

Or with JQuery:

function ResetFormWithJS() {
    $("[asp-for='Name']").val("");
    $("[asp-for='Email']").val("");
}

What is happening here and how can I make all fields always reset, regardless of whether or not there were any model errors? Additionally, I would like to have the model errors disappear on reset too.

To achieve the requirement, you can try to reference _ValidationScriptsPartial.cshtml to support client-side validation, which would also help avoid an unnecessary round trip to the server.

@section Scripts {
    <partial name="_ValidationScriptsPartial" />
}

Test Result

enter image description here

Related