I'm facing an issue with sending JSON data from a JavaScript function to a C# method using Ajax. When I receive the data in C#, it's not being recognized as JSON. How can I resolve this issue? If I try to output the received data using Response.Write(arr) in C#, it shows up as System.string[]. My project is built on MVC 3.
C# Method
public int save(string[] arr)
{
SqlConnection connection = new SqlConnection(WebConfigurationManager.ConnectionStrings["strConnection"].ToString());
connection.Open();
SqlTransaction transaction = connection.BeginTransaction();
try
{
// Truncate client_resource table
dtsResourceClientTableAdapters.RESOURCE_CLIENTTableAdapter table = new dtsRecursoClienteTableAdapters.RECURSO_CLIENTETabelaTableAdapter();
for (int j = 0; j <= 149; j++) {
table.Insert(arr);
}
transaction.Commit();
return 1;
}
catch (SqlException ex)
{
try
{
transaction.Rollback();
return 0;
}
catch (Exception exRollback)
{
return 0;
}
}
}
JavaScript Function + Ajax
$("#btnSave").on("click", function () {
var confirmSave = confirm("Do you want to save the data?");
if (confirmSave) {
var list = jQuery("#resourceTable").getDataIDs();
var totalItems = list.length;
var arr = [];
for (var i = 1; i <= list.length; i++) {
var rowData = $("#resourceTable").jqGrid('getRowData', i);
if (rowData.CD_CLIENT != 0) {
arr[i - 1] = {
col1: rowData.CD_RESOURCE,
col2: rowData.NAME_RESOURCE,
col3: rowData.CD_CLIENT,
col4: rowData.EMAIL_LIST,
col5: rowData.COPIED_EMAIL_LIST
}
}
}
$.ajax({
type: 'POST',
url: '/Pages/save',
contentType: "application/json; charset=utf-8",
data: JSON.stringify(arr),
dataType: 'json',
success: function (data) {
if (data == 0) {
alert("Unable to save the data");
}
}
});
}
});