How can I make an asp.net mvc checkbox trigger an action?
You will need ajax for this. First, add a class to the checkboxes so you will have a hook to attach your click event.
@Html.CheckBoxFor(modelItem => item.Claimed, new { id = item.Macro_Name, @class = "toggle" data_url = Url.Action("ToggleClaim", "MacroStatus")})
Now add your javascript.
@section scripts {
<script>
$(function() {
$('.toggle').change(function() {
var self = $(this);
var url = self.data('url');
var id = self.attr('id');
var value = self.prop('checked');
$.ajax({
url: url,
data: { id: id },
type: 'POST',
success: function(response) {
alert(response);
}
});
});
});
</script>
}
The key point is sending an ajax request when checkbox changed.
As mentioned in comments by Eric, You can trigger that action using many different ways. for example, put this script in your codes:
<script>
$(function () {
$('#Claimed').change(function () {
$.ajax({
url: '/ToggleClaim/MacroStatus/@item.Macro_Name',
cache: false,
method: 'GET',
success: function (data) { alert('success'); },
error: function () { alert('error'); }
});
});
});
</script>
And correct checkbox code this way:
<td>
@Html.CheckBoxFor(modelItem => item.Claimed)
</td>
The above code, triggers the action each time you check or uncheck the checkbox, you can simply check if the checkbox is checked and then send ajax request.