I have created an array of objects in JavaScript and need to send them back to the server using Ajax (jQuery is being used)
This is how the object array looks like in JavaScript:
var columns = [
{ name: 'col 1', source: 'whatever', hidden: false, width: 50 },
...
];
The data is being sent back this way:
$.post('/MyController/MyAction', { 'columns': columns });
When I receive it in the controller action, this is what I am currently getting:
I have a c# object named JqColumn
where I want to bind the posted data into, it has the following structure:
public class JqGridColumn
{
public string name;
public string source;
public int width;
public bool hidden;
}
I assumed that adding a parameter in the controller action of type JqGridColumn[] columns
would automatically bind the posted data, but unfortunately it's not working as expected (it creates an array with the correct number of elements, but each item has empty values)
Could someone guide me on what step I might be missing? Thank you!
UPDATE
Currently, I am manually mapping the items in my controller action like this:
public void ColumnChooser(JqGridColumn[] columns)
{
for (int i = 0; i < columns.Length; i++)
{
columns[i].hidden = bool.Parse(Request.Form["columns[" + i + "][hidden]"]);
columns[i].width = int.Parse(Request.Form["columns[" + i + "][width]"]);
columns[i].name = Request.Form["columns[" + i + "][name]"];
columns[i].source = Request.Form["columns[" + i + "][source]"];
}
return;
}
...this approach works well, but I am interested in learning the correct .Net MVC way to achieve this!