I am trying to send stringified array from view with $.ajax but I am constantly getting null in controller. This is controller function:
[HttpPost]
public void SaveColumnsToDb(string data)
{
var a = data;
}
Console outputs:
str: (2) ['SerialNumber', 'MeasurementUnit']
JSON str: ["SerialNumber","MeasurementUnit"]
Whole function:
$("#popup-saveBtn").click(function () {
var columns = [];
var parentElement = document.getElementById("tableColumns");
var childElements = parentElement.querySelectorAll("input[type=checkbox]");
// If checkbox is checked, push value to array
for (i = 0; i < childElements.length; i ) {
if (childElements[i].checked) {
columns.push(childElements[i].value);
}
}
/*var strColumns = columns.join(";");*/
console.log("str: ", columns);
console.log("JSON str: ", JSON.stringify(columns));
// Send data to AjaxSelectController
$.ajax({
url: '@Url.Action("SaveColumnsToDb", "AjaxSelect", new { area = string.Empty })',
type: 'POST',
data: JSON.stringify(columns),
dataType: 'json',
contentType: 'application/json; charset=utf-8'
});
});
CodePudding user response:
as a matter of fact, since you are using contentType: 'application/json; charset=utf-8', you are trying to send a json inside of the request body, so use this syntax
[HttpPost]
public void SaveColumnsToDb([FromBody] string[] data)
CodePudding user response:
Changed the parameter name. When we use an ajax request then we have to pass value in data and In the URL part, we have to give only the action name and controller name.
[HttpPost]
public void SaveColumnsToDb(string dataResponse)
{
var a = dataResponse;
}
$("#popup-saveBtn").click(function () {
var columns = [];
var parentElement = document.getElementById("tableColumns");
var childElements = parentElement.querySelectorAll("input[type=checkbox]");
// If checkbox is checked, push value to array
for (i = 0; i < childElements.length; i ) {
if (childElements[i].checked) {
columns.push(childElements[i].value);
}
}
/*var strColumns = columns.join(";");*/
console.log("str: ", columns);
console.log("JSON str: ", JSON.stringify(columns));
// Send data to AjaxSelectController
$.ajax({
url: '@Url.Action("SaveColumnsToDb", "AjaxSelect")',
type: 'POST',
data: { dataResponse: JSON.stringify(columns)},
dataType: 'json',
contentType: 'application/json; charset=utf-8'
});
});
CodePudding user response:
I managed to make it work.
Changed data property in $.ajax().
data: JSON.stringify({ data: strColumns })
I am sending only csv string, e.g. "abc;abc;abc" Controller is same.