How to make controller action method for this ajax function with SQL Server stored procedure:
<script type="text/javascript">
// event to fire on Save button click //
$(document).on('click', '#btnSave', function () {
var data = HTMLtbl.getData($('#example-1'));
var parameters = {};
parameters.array = data;
var request = $.ajax({
async: true,
cache: false,
dataType: "json",
type: "POST",
traditional: true,
contentType: "application/json; charset=utf-8",
url: "/index/SaveData",
data: JSON.stringify(parameters)
});
});
Function to convert HTML table to jagged array and how to make action result in controller
var HTMLtbl =
{
getData: function (table) {
var data = [];
table.find('tr').not(':first').each(function (rowIndex, r) {
var cols = [];
$(this).find('td').each(function (colIndex, c) {
cols.push($(this).text().trim()); // get td Value
});
data.push(cols);
});
return data;
}
}
</script>
In aspx web form I make this to work with webmethod:
public static string SaveData(string[][] array)
{
string result = string.Empty;
try
{
DataTable dt = new DataTable();
dt.Columns.Add("Month");
dt.Columns.Add("Week");
dt.Columns.Add("Area");
foreach (var arr in array)
{
DataRow dr = dt.NewRow();
dr["Month"] = arr[0];
dr["Week"] = arr[1];
dr["Area"] = arr[2];
dt.Rows.Add(dr);
}
}
and then I use SQL Server stored procedure to insert at once :
SqlCommand cmd = new SqlCommand();
cmd.CommandType = CommandType.StoredProcedure;
cmd.CommandText = "proc_one";
cmd.Connection = cnn;
cmd.Parameters.Add("@TableType", SqlDbType.Structured).SqlValue = dt;
result = cmd.ExecuteNonQuery().ToString();
now i get Request failed: parsererror with this code :
[HttpPost]
public JsonResult SaveData(string array)
{
using (MY_DB_1Entities dc = new MY_DB_1Entities())
{
if (array != null && array != "")
{
//Edit
Employee emp = JsonConvert.DeserializeObject<Employee>(array);
dc.Employees.Add(emp);
dc.SaveChanges();
}
}
return Json(false, JsonRequestBehavior.DenyGet);
}
when i turn off datatype:json from ajax i get rows save undefined