0

I have a list of checkboxes and I want to run a function when they are clicked.

<table class="table">
    <tr>
        <th>
            @Html.DisplayNameFor(model => model.RequiresSetup)
        </th>
    </tr>

    @foreach (var item in Model)
    {
        <tr>
            <td>
                @Html.CheckBox("RequiresSetup", item.RequiresSetup) 
            </td>
        </tr>
    }
</table>

So far I am using @Html.CheckBox(String, bool), but this is not enough. After checking the InputExtensions.CheckBox Method Documentation I also do not see a way out of it.

I want to detect when a user checks or unchecks a certain checkbox, so I can call a function that immediatly saves the change in the database.

After my research I also believe I need something like this:

void Handle_Clicked(Object sender, EventArgs e) {
    //save to DB
}

But I have no idea on how to tell CheckBox "i" to that that funcion accordingly.

How do I proceed?

Flame_Phoenix
  • 16,489
  • 37
  • 131
  • 266
  • You need to use javascript/jquery to handle the click event of the checkbox and submit the form. Note the code you have shown for `Handle_Clicked` is web forms, not MVC. –  Nov 04 '14 at 10:17
  • `Handle_Clicked` belongs to the WebForms technology. You are using MVC which doesn't have it. To handle a click, [attach a click event handler](http://api.jquery.com/on/) to the checkbox with JavaScript. Also note your code will not make sense to the model binder when you post your form, because all check boxes are going to have same names and IDs. – GSerg Nov 04 '14 at 10:17

1 Answers1

2

As it's ASP.Net MVC (and not webforms) you can't write server-side events. Instead, what you should do is catch the "click" event using javascript, then make an AJAX call (POST) to execute an action in a controller.

For example here is how you would catch the event client side using JQuery: https://stackoverflow.com/a/3442342/870604

And here is an example of an AJAX call to execute an action on your controller: Proper way to use AJAX Post in jquery to pass model from strongly typed MVC3 view

Community
  • 1
  • 1
ken2k
  • 48,145
  • 10
  • 116
  • 176