Save changes on CheckBox change?

Shimmy Weitzhandler picture Shimmy Weitzhandler · Nov 13, 2012 · Viewed 8.6k times · Source

I have an MVC Index page that reflects a table in the DB.
One of the columns is a boolean.
I want to have a checkbox right in the index page, that when clicked, immediately calls an action that will save the new status on the spot without having to submit/refresh.

Answer

Justin Helgerson picture Justin Helgerson · Nov 13, 2012

You should add an onclick event to the input. Your razor would look similar to:

@Html.CheckBoxFor(m => m.Foo, new { onclick = "SomeMethod(this)" });

Then your script would look similar to (assuming you have access to jQuery; converting it should be straight forward enough):

function SomeMethod(checkboxInput) {
    $.ajax({
      type: 'POST',
      url: Your/Action,
      data: { newValue: checkboxInput.checked },
      success: success,
      dataType: 'json'
    });
}

Notice the parameter name: newValue.

And finally your Action to handle the request:

public JsonResult Action(bool newValue) {
   //Do your stuff!
   //repository.Update();
}

Notice the parameter name: newValue.