Search code examples
asp.net-mvccheckboxsubmitactionlinkcheckboxfor

Save changes on CheckBox change?


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.


Solution

  • 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.