I have the following JavaScript that renders a checkmark if data == true or an X if data == false:
{
data: "HasPayment",
render: function (data, type, row) {
var paymentSet = '@Url.Action("Set", "Payment")?applicationId=' + row.Id + '&year=' + row.Year + '&month=' + row.Month + '&hasPayment=' + data;
if (data) {
return '<a href=\"' + paymentSet + '\" <span class="fas fa-solid fa-check" style="color: green"></span>';
}
return '<a href=\"' + paymentSet + '\" <span class="fas fa-solid fa-times" style="color: red"></span>';
}
}
When the checkmark or X Url.Action is clicked, it calls the following method:
public void Set(Guid applicationId, int year, int month, bool hasPayment)
{
using (var db = new DbContext())
{
var paymentMoYear = year * 100 + month;
var payment = db.Payments.Where(p => p.ApplicationId == applicationId && p.PaymentMoYear == paymentMoYear).FirstOrDefault();
if (hasPayment)
{
db.Payments.Remove(payment);
}
else
{
if (payment == null)
{
payment = new Payment
{
ApplicationId = applicationId,
PaymentMoYear = paymentMoYear,
};
db.Payments.Add(payment);
}
else
{
payment.IsDeleted = false;
}
}
db.SaveChanges();
}
}
Can I redraw my datatable after the Url.Action checkmark/X is clicked? The desired result is that a user clicks the Url.Action and the checkmark is changed to an X or the X is changed to a checkmark. The datatable is then redrawn to display the change.
I know that I can redraw my datatable when a button is clicked:
HTML Input Button:
<td>
<input type="button" value="Search" id="btnPaymentSearch" />
</td>
JavaScript Button Click Function:
$("#btnPaymentSearch").click(function () {
paymentDataTable.columns(2).search($("#numHR_pAppNumber").val().trim());
paymentDataTable.columns(4).search($("#txtHR_pClient").val().trim());
--more code--
paymentDataTable.draw();
});
However, I am using a Url.Action link in this example.
What you can do here is add a class to the anchor tag and then register the click event for it :
if (data) {
return '<a class="payment" href=\"' + paymentSet + '\" <span class="fas fa-solid fa-check" style="color: green"></span>';
}
return '<a class="payment" href=\"' + paymentSet + '\" <span class="fas fa-solid fa-times" style="color: red"></span>';
and then write the event for this element in which we can send an ajax call to the url specified in the href and in the success event we can draw the datatable again like:
$(document).on("a.payment","click",function(){
$.ajax({
url: $(this).attr("href")',
contentType: "application/json; charset=utf-8",
dataType: "json",
success: function(response) {
paymentDataTable.draw();
},
error: function() {
// handle error
}
});
});