Reputation: 465
I am attempting to pass an array of objects from my view to the controller with AJAX. The array is not being passed to the controller (the controller action receives null).
function submitFilters() {
var filters = [];
$(".filter-option-checkbox").each( function(){
var filter =
{
FilterType: $(this).find("#filter_Type").val().toString(),
FilterDescription: $(this).find("#filter_Description").val().toString(),
OptionDescription: $(this).find("#option_Description").val().toString(),
OptionSelected: $(this).find(".custom-control-input").prop('checked')
};
filters.push(filter);
});
$.ajax({
type: 'POST',
url: '@Url.Action("Index", "Category")',
data: JSON.stringify(filters),
dataType: "json",
contentType: "application/json; charset=utf-8",
success: function (view) {
},
failure: function (response) {
}
});
}
[HttpPost]
public IActionResult Index(FilterJSON[] filters)
{
//...code here...
}
public class FilterJSON
{
public string FilterType { get; set; }
public string FilterDescription { get; set; }
public string OptionDescription { get; set; }
public bool OptionSelected { get; set; }
}
I don't think I'm far off. What am I missing? Thank you.
Upvotes: 2
Views: 680
Reputation: 551
[HttpPost]
public IActionResult Index([FromBody]FilterJSON[] filters)
{
//...code here...
return null;
}
and
$.ajax({
type: 'POST',
url: '@Url.Action("Index", "Home")',
data: JSON.stringify(filters),
contentType: "application/json; charset=utf-8",
success: function (view) {
},
failure: function (response) {
}
});
should work
Upvotes: 1
Reputation: 1186
You need to use a ViewModel with a List inside:
public class YourViewModel
{
public List<FilterJSONItem> FilterJSON{ get; set; }
}
public class FilterJSONItem
{
public string FilterType { get; set; }
public string FilterDescription { get; set; }
public string OptionDescription { get; set; }
public bool OptionSelected { get; set; }
}
public ActionResult Method([FromBody]YourViewModel vm)
{
}
Upvotes: 1