Hanna
Hanna

Reputation: 10753

Resetting form based on ASP.NET model

I have a form that uses a model to populate some of the fields.

I have a list of checkboxes, and I want a reset button that resets all the checkboxes to what they were when the page loaded. How can I refresh that form with the current model, effectively erasing any changes made?

For example, there are three checkboxes, box 1 is checked and 2 and 3 are not. A user checks 2 and 3 but can't remember what he changed and doesn't want to change anything bad, so he wants to hit a reset button that will restore the checkmarks to default while still remaining on the form.

I'm sure some ajax will be involved but I can't see how to reload the page using the current model.

Is this even possible?

Upvotes: 0

Views: 315

Answers (2)

Dave Alperovich
Dave Alperovich

Reputation: 32500

One method is to render your checkboxes with an Action Partial. An Action Partial is a call to an ActionResult Method which returns a (optional) Model or Viewbag to the Partial View. The Partial View can use the passed logic to decide how to set and render the checkboxes.

<div id='divchkbox'>
    @Html.Action("/Tools/checkboxes/{id}")
</div>

link and event handler

     $(document).ready(function () {

          $('#resetbtn').click(function(){
               $('divchkbox').load("/Tools/checkboxes/{id}");
          }
   });

Upvotes: 1

Split Your Infinity
Split Your Infinity

Reputation: 4229

You can store the original values in a data attribute. See example. This way you don't have to go back to the server (and show a loading indicator, handle the error case, etc), because you have a copy of the original values before they changed.

HTML

<input type="checkbox" checked data-was-checked="checked">Option 1</input>
<input type="checkbox">Option 2</input>
<input type="checkbox" checked data-was-checked="checked">Option 3</input>
<input type="checkbox">Option 4</input>
<button id="reset">Reset</button>

JAVASCRIPT

$("#reset").click(function () {
    $("[type=checkbox]").each(function (index, cb) {
        cb.checked = !!cb.getAttribute("data-was-checked");
    });
});

Upvotes: 2

Related Questions