0
votes

I'm struggling with form clear after submit search boxes in my .net Core - Razor Pages web app. I need to persist searched values after onPostAction which are called from form submit button.

Here is my index.cshtml (simplified to one searchbox and 2 buttons - post & clear filter)

    <form method="post">
      <div class="form-group form-inline row ">
        <label class="col-md-2 font-weight-bold control-label">Phone Number</label>
        <input type="search" name="searchPhoneNumber" value="@ViewData["sPhoneNumber"]?.ToString()"/>
      </div>
      <div class="form-group form-inline row ">
        <input type="submit" value="Search"/>
        <button type="reset" onclick="$this.form.reset()">Clear All</button>
    </div>

Then in my index.cshtml.cs I have OnPostAsync task (again simplified)

[ViewData]
public string sPhoneNumber{ get; set; }
public async Task OnPostAsync(string searchPhoneNumber)
{
if (!String.IsNullOrEmpty(searchAlcatel))
        {
            records = records.Where(s => s.PhoneNumber.Contains(searchPhoneNumber));
            ViewData["sPhoneNumber"] = searchPhoneNumber;
        }
        else { ViewData["sPhoneNumber"] = ""; }
}
Model = await records.AsNoTracking().OrderBy(item => item.Surename).ToListAsync();

Now the problem. This way form keeps data values from client after submit button fires OnPost method, which is what I need. But !!! also this solution breaks functionality of "reset" button, because it cannot clear value from that search input. Moreover, If I manualy clear value of that search box and hit the "reset" button, it spawns lastly used value back in the field, which is definitelly not what I want.

Is there any way how to keep form values after submit and also make "reset" button working on form data values in same time please?

Thank you very much in advance for any kind of help.

1
Maybe its an idea to save them in local storage, and fill the form with it if they have a value. On reset clear local storage. Related: stackoverflow.com/questions/17087636/…rank
It sounds like you need to write reset manually in JavaScript.Aluan Haddad
document.querySelector('input[name=searchPhoneNumber]).value = nullAluan Haddad

1 Answers

0
votes

I solve this as @Aluan Haddad suggested. To reset values I had to make custom function in javascript:

<script type="text/javascript">
            function resetForm() {
                document.getElementById("searchPhone").value = "";
                document.getElementById("searchFax").value = "";
            }
        </script>

and call it from onClic action like (onclick="resetForm()")

Now it works fine for me... Thank you very much for help !