Reputation: 17594
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?
Upvotes: 0
Views: 6667
Reputation: 49013
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
Upvotes: 2