I'm able to post a complex object to an ASP.NET MVC controller with jQuery, as long as I modify the output of $.param() like this: "Column[0][Name]" -> "Column[0].Name"
However, this only works if the data is bound to an array-type property on the server (Columns1 in the example below). A collection type like IEnumerable or the EntitySet used by LINQ-to-SQL doesn't work.
Should I simply define a write-only array-type property that sets the EntitySet property on binding, or is there a more elegant solution?
JavaScript
var columns =
[
{ Name: 'Alpha', Width: 50 },
{ Name: 'Bravo', Width: 100 },
{ Name: 'Charlie', Width: 75 }
];
var params = $.param(
{
Name: 'MyTable',
Columns1: columns,
Columns2: columns,
Columns3: columns
} );
params = params.replaceAll( '%5BName%5D=', '%2EName=' );
params = params.replaceAll( '%5BWidth%5D=', '%2EWidth=' );
$.post( $.getUrl( '/MyController/CreateTable/' ),
params,
function()
{
$.log( 'done' );
} );
Domain classes
public class Table
{
public string Name { get; set; }
public Column[] Columns1 { get; set; }
public IEnumerable<Column> Columns2 { get; set; }
public EntitySet<Column> Columns3 { get; set; }
}
public class Column
{
public string Name { get; set; }
public int Width { get; set; }
}
Controller action
public ActionResult CreateTable( Table table )
{
// table.Columns1 contains a list of three Columns, with Name and Width set properly
// table.Columns2 and table.Columns3 both contain three Column objects, but Name and Width are null/0
}
EDIT
Replaced replace() string function with replaceAll(), as seen here.