I am using MVC5 with Ado.net datatable. I have a method in a Controller. I would like to use an ajax call to send form data to this method. i want to call this method in my create action when creating new records, so I can just pass the collection of datarows in the datatable to create multiple records simultaneously.
This is how my method looks
DataTable dt = new DataTable();
public void InsertRecord(FormCollection collection)
{
if (dt.Columns.Count == 0) // if no columns defined
{
//create columns
dt.Columns.Add("Name", typeof(string));
dt.Columns.Add("Length", typeof(double));
dt.Columns.Add("Breadth ", typeof(double));
dt.Columns.Add("Height ", typeof(double));.
dt.Columns.Add("IsMeasured ", typeof(bool));
}
if (collection != null)
{
DataRow row = dt.NewRow();
row.SetField<string>("Name", collection["Name"]);
row.SetField<double>("Length", Convert.ToDouble(collection["Length"]));
row.SetField<double>("Breadth", Convert.ToDouble(collection["Breadth"]));
row.SetField<double>("Height", Convert.ToDouble(collection["Height"]));
row.SetField<bool>("IsMeasured", Convert.ToBoolean(collection["IsMeasured"]));
dt.Rows.Add(row);
}
}
my ajax call looks like:
function AddItem() {
var inputs = $('#DetailCard input, #DetailCard select').serialize();
$.ajax({
type: 'POST',
url: '/CreateRecords/InsertRecord',
data: inputs,
dataType: 'json',
success: function (info) {
if (info.result == "Error") {
alert(info.message);
}
}
});
};
my submit button:
<input type="button" value="Add" onclick="AddItem()" />
When I run the project I can see the first two column fields of the data row (Name and Length) are filled (populated). However when the program gets to the "Breadth" column it crashes and gives an error (System.ArgumentException ... 'Breadth' does not belong to table). I have double checked everything but cannot see what I am missing.
Your code sample above has a space after the name (ie "Breadth ", not "Breadth") when you are creating the table; the name of the column must match exactly.
Extra space after these 3 for the name:
Change to: