0

I have a Create View form in an MVC5 application and after creating a record I redirect to another view called Completed. If the user click back button of the web browser, the previous data retains and I cannot clear the form fields using the following methods below:

View:

document.getElementById("frmCreate").reset();

or

$('#frmCreate').trigger("reset");

or

$("#frmCreate")[0].reset();

I also tried to clear ModelState in the controller, but does not make any sense.

Controller:

//code omitted for brevity

db.Visitors.Add(visitor);
db.SaveChanges();

// This will clear whatever form items have been populated
ModelState.Clear();

return RedirectToAction("Completed");

Any idea except from the above in order to clear all of the form elements?

Jack
  • 1
  • 21
  • 118
  • 236
  • can you please post your html ... atleast to get the idea of form and input fields – Bhushan Kawadkar Aug 23 '16 at 07:10
  • 1
    Check [this](http://stackoverflow.com/questions/6364289/clear-form-fields-with-jquery) , may be useful to you – Bhushan Kawadkar Aug 23 '16 at 07:16
  • @BhushanKawadkar Sorry, I am out of office now, but I use Html.TexboxFor and similar razor components in the form. – Jack Aug 23 '16 at 07:33
  • AFAIK, elements bound for a model (TextBoxFor, DropDownListFor etc) will retain its value on postback until the model contents has cleared from the controller side. You can pass an empty model like `return View(new ViewModel())` when user pressing back button or use `RedirectToAction("url")` when handling postback request. – Tetsuya Yamamoto Aug 23 '16 at 08:29
  • Could you please give an example to use the code instead of RedirectToAction("url")? – Jack Aug 23 '16 at 09:29
  • **$(this).closest('form').find("input[type=text], textarea").val("")** worked for TexBoxes. But I also need to clear (select first child element) of Dropdownlists (DropDownListFor) and DateTimePickers. Any idea? – Jack Aug 23 '16 at 09:54

1 Answers1

1

Use the following function in you script,

 $(window).load(function() {
         $('form').get(0).reset(); //clear form data on page load
     });
NaN
  • 1,012
  • 3
  • 13
  • 25
  • This actually didn't work for me. I ended up using this: `window.addEventListener('load', function () { document.querySelector('form.search-form').reset(); });` and avoiding jQuery altogether for this. – ahwm Jul 25 '19 at 18:02