Reputation: 390
I am using .Net Core razor for my application.
When I call the controller action from my Ajax, the value I pass comes null to the controller.
Here is my script:
var table = $('#dataTable').DataTable();
var data = table.$('input[type="checkbox"]').serializeArray();
console.log(data);
var data_json = JSON.stringify({ 'data_json': data });
console.log(data_json);
$.ajax({
contentType: "application/json; charset=utf-8",
dataType: 'json',
type: "GET",
url: '@Url.Action("UpdateChart","Home")',
data: data_json,
cache: false,
success: function (result) {
myFunction(result);
chart.render();
console.log(result);
}
});
}
I simply get the values of selected checkboxes and convert them into JSON.
My Controller is:
[HttpGet]
public JsonResult UpdateChart(List<CheckBoxArray> data_json)
{
ChartRepository repository = new ChartRepository();
string deviceSerialNo = HttpContext.Session.GetString("currentSerialNumber") != null ? HttpContext.Session.GetString("currentSerialNumber").ToString() : "1606008363";
string query = repository.PrepSelectQuery("1", deviceSerialNo, "2021-03-04 10:04:55.544398", "2021-03-05 10:46:55.544398");
GeneralObjects.ServiceResponse response = repository.GetChartData(query);
TempData["AllData"] = response.This_Object;
return Json(new { myData = response.This_Object.ToString() });
}
public class CheckBoxArray
{
public string Name { get; set; }
public string Value { get; set; }
}
Here the List data_json comes empty. However, the data is like:
{"data_json":[{"name":"chkBox","value":"1"},{"name":"chkBox","value":"4"},{"name":"chkBox","value":"7"}]}
What's the problem here I have that can't get the value?
Upvotes: 0
Views: 375
Reputation: 27803
When I call the controller action from my Ajax, the value I pass comes null to the controller.
Based on your code, we can find that you'd like to pass a list of CheckBoxArray
object from ajax client side to controller, and you set request method to GET
, which would pass the data through query string.
To achieve the requirement and make the data can be bound to action parameter List<CheckBoxArray> data_json
as expected, you can try to modify the client side code to dynamically generate query string based on your json arrary data, like below.
var qparam = "";
for (var i = 0; i < data.length; i++) {
qparam += "data_json[" + i + "].name=" + data[i].name + "&data_json[" + i + "].value=" + data[i].value + "&";
}
$.ajax({
contentType: "application/json; charset=utf-8",
dataType: 'json',
type: "GET",
url: '@Url.Action("UpdateChart","Home")?' + qparam.substring(0, qparam.length - 1),
cache: false,
success: function (result) {
myFunction(result);
chart.render();
console.log(result);
}
});
For detailed information about model binding and how it works, please check this doc: https://learn.microsoft.com/en-us/aspnet/core/mvc/models/model-binding?view=aspnetcore-5.0#collections
Test Result
Upvotes: 1