views:

67

answers:

1

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.

A: 

Here's an example of the fix I referred to in my question. It works, but would need to be implemented for all similar properties.

"Generated" LINQ-to-SQL domain class

public partial class Table
{
    public string Name { get; set; }
    public EntitySet<Column> Columns { get; set; }
}

Partial class with jQuery-friendly array property

public partial class Table
{
    public Column[] ColumnsIn
    {
        get
        {
            // ASP.NET MVC requires a getter in all bound properties, but the returned value isn't used in this case
            return null;
        }
        set
        { 
            Columns = new EntitySet < Column > ();
            Columns.AddRange ( value );
        }
    }
}
MikeWyatt