3

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.

Shimmy Weitzhandler
  • 101,809
  • 122
  • 424
  • 632

1 Answers1

11

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.

Justin Helgerson
  • 24,900
  • 17
  • 97
  • 124
  • Thanks. As I'm new to MVC, please help me in the following: 1) Where should place the JS snippet? 2) Please elaborate what goes in the `JsonResult` 3) Isn't there a JS-free way? – Shimmy Weitzhandler Nov 13 '12 at 05:05
  • The script, such as `SomeMethod` can go wherever you would like. You could put it on the page itself, or as I often do is you can place it in an external file and load that file on page load. The JsonResult should contain your code to actually perform the update or save to the database what you want to perform. – Justin Helgerson Nov 13 '12 at 05:09
  • 1
    If you want to include it in the view itself, I would place the script at the end of the body. The return type of your JsonResult can be whatever you need to take appropriate action on the client side. For now, you could just return a boolean: `return Json(true);`. – Justin Helgerson Nov 13 '12 at 05:25
  • Followed the exact steps, Can't get the action to be fired on checkbox state change onclick, Anyway you can include larger code part with the js libraries needed, Saving the state in the action both for checked/unchecked - save it to session or viewbag. But start with firing the json script which doesn't call the action stated onclick. – JBntis May 05 '13 at 08:21