I have the following javascript snippet:
$.ajax({
url: self.LoadCirculationListUrl,
cache: false,
async: false,
dataType: 'json',
contentType: 'application/json; charset=utf-8',
data: [ { "ColumnName":"France","Comparitor":"=","Value":"1"},{"ColumnName":"Germany","Comparitor":">","Value":"3"}]
});
Here is the controllre which is accessed from the above ajax call:
public ActionResult LoadCirculationData(IList<CirculationListFilter> filters)
{
}
Here is the CirculationListFilter class
public sealed class CirculationListFilter
{
public string ColumnName { get; set; }
public string Comparitor { get; set; }
public string Value { get; set; }
}
Now when I run the code, the controller does not get the JSON collection passed to it; filters is always null. However, if I do this:
$.ajax({
url: self.LoadCirculationListUrl,
cache: false,
async: false,
dataType: 'json',
contentType: 'application/json; charset=utf-8',
data: { "ColumnName":"Germany","Comparitor":">","Value":"3"}
});
and the contoller is like this:
public ActionResult LoadCirculationData(CirculationListFilter filters)
{
}
The data is passed fine. Why can’t the controller bind a collection of JSON items?
EDIT:
I changed the AJAX call to use this:
data: { filters: [{ "ColumnName": "France", "Comparitor": "=", "Value": "1" }, { "ColumnName": "Germany", "Comparitor": ">", "Value": "3" }]},
and the ActionResult:
public ActionResult LoadCirculationData(List<CirculationListFilter> filters)
Now filters has 2 items inside of it, but each of the CirculationListFilter classes are populated with NULL data in their properties. So I’m getting closer, but the actual values are not being binded.
The problem is in the .ajax() call.
.ajax() doesn’t convert the data into JSON string.
The reason why it works for one item is because .ajax() was able to convert the data into a query string which MVC happily accepted.
The solution is to convert the JSON into string first: