I'm trying to use ajax to post to a controller when a checkbox is clicked. It should update an existing object. My two problems are:
- I cannot successfully call the controller action method
- Only the first item in a list has the click event
Hopefully someone can help out
On click event with ajax
$('#checkboxID').on('click', function () {
$.ajax({
url: '@Url.Action("Attending", "GuestBookings")',
type: 'POST',
data: JSON.stringify({
"cID": $(this).val('cID'), "eID": $(this).val('eID'), "check": $(this).is(':checked') ? 1 : 0
}),
success: function(result) {
alert("Succeeded post");
},
error: function(result) {
alert("Failed to post");
}
});
});
Controller HttpPost
[HttpPost]
[ValidateAntiForgeryToken]
public async Task<IActionResult> Attending(string cID, string eID, string check)
{
if (ModelState.IsValid)
{
var guest = await _context.Guests
.Where(g => g.CustomerId.ToString() == cID && g.EventId.ToString() == eID).FirstOrDefaultAsync();
if (check == "0")
{
guest.Attended = false;
}
else
{
guest.Attended = true;
}
try
{
_context.Update(guest);
await _context.SaveChangesAsync();
}
catch (DbUpdateConcurrencyException)
{
}
}
return Json(true);
}
Checkbox
<tbody>
@foreach (var item in Model.GuestsBooked)
{
<tr>
<td>
@Html.DisplayFor(modelItem => item.Surname)
</td>
<td>
@Html.DisplayFor(modelItem => item.FirstName)
</td>
<td>
@Html.DisplayFor(modelItem => item.Email)
</td>
<td>
@Html.CheckBoxFor(modelItem => item.Attended, new { @id = "checkboxID", @cID = item.Id, @eID = Model.Id })
</td>
<td>
@Html.ActionLink("Details", "Details", "Customers", new { id = item.Id }) |
@Html.ActionLink("Unbook", "Delete", "GuestBookings", new { id = item.Id, eventId = Model.Id }) |
</td>
</tr>
}
</tbody>