Adding a new row to jQuery datatable and posting data

Home / Uncategorized / Adding a new row to jQuery datatable and posting data

Question:
I’ve got a datatable that I am adding a row to like this:function AddRow(controller) {
var table = $(‘#’ + controller + ‘_data_table’).DataTable();

var index = table.rows()[0].length;

var previousRowDate = $("input[name='[" + (index – 1) + "].Date’]").val();
var userID = $("input[name='[" + (index – 1) + "].UserID’]").val();

var date = new Date(previousRowDate.replace(‘-‘, ”));
date.setDate(date.getDate() + 1);

if (isNaN(date)) {
date.setDate(new Date());
}

var rowNode = table
.row.add(["",
"",
"",
""

])
.draw()
.node();

$(rowNode)
.css(‘color’, ‘red’)
.animate({ color: ‘black’ });

$(".daterangepicker").datepicker(
{
dateFormat: "dd-M-yy",
changeMonth: true,
changeYear: true,
minDate: 0
});
}

This adds a row, on a button click I post the data from the datatable to save to the DB, like this:function Update(controller) {
var table = $(‘#’ + controller + ‘_data_table’).dataTable();

var model = table.$(‘*’).serializeArray();
$.each(model, function (i, fd) {
var value = fd.value;
value = value.replace(//g, ">"); //for >

fd.value = value;
});

$.post("/" + controller + "/Update", model)
.done(
function (data) {

if (data.ErrorOccurred) {
bootbox.alert(data.Message);
}
else if (data.Success) {
bootbox.alert(data.Message);
$(‘#’ + controller + ‘_update’).prop(‘disabled’, true);
}
$(‘#’ + controller + ‘_details’).html(data.View);
});
}

Server side code:[HttpPost]
public ActionResult Update(List effort)
{
try
{
effort.ForEach(item =>
{
var effortInDB = _context.Targets.SingleOrDefault(t => t.Id == item.Id);
if (effortInDB == null) return;
effortInDB.Date = item.Date;
effortInDB.Min = item.Min;
effortInDB.Max = item.Max;
});
_context.SaveChanges();

return Json(new
{
ErrorOccurred = false,
Message = ""
});

}
catch (Exception exception)
{
return Json(new
{
ErrorOccurred = true,
Message =
$"An error occurred: {System.Environment.NewLine}{exception.Message}"
});
}
}

The issue I am having is that userId is 0 on the server side code, event though I’ve created my hidden field with the value of it.

I need the id to save it in the DB


Answer:

Read more

Leave a Reply

Your email address will not be published. Required fields are marked *