Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Passing a collection of objects to MVC controller using $.post

We are trying to send a collection of objects from our page to our controller (MVC 3) using json and the jQuery .post function. Below is our js code and the controller and object definitions.

The problem is that while the object is being sent to our controller appropriately, it's member variables are not being populated. The "Coords" list has the appropriate number of "Coord" objects but each Coord object's member variables are populated with zero (not null) instead of the values we are passing in. See the screenshot:

Any ideas what is wrong with our implementation?

Thanks in advance!

enter image description here

Coord1 = { "X": 100, "Y": 200 };
Coord2 = { "X": 300, "Y": 400 };

zoneData = { "Color": "#D8F834", "Name": "new zone", "Coords": [Coord1, Coord2] }

$.post("/Demo/SaveZone", zoneData, function (resp) {
     alert(resp);
}, "json");





[HttpPost]
public ActionResult SaveZone(ZoneViewModel zvm)
{
     Zone z;

     z = AutoMapper.Mapper.Map<ZoneViewModel, Zone>(zvm);

     _db.Zone.Attach(z);
     _db.SaveChanges();

     return View();
}


public class ZoneViewModel
{

    public int Id { get; set; }
    public string Name { get; set; }
    public string Color { get; set; }

    public CoordViewModel[] Coords { get; set; }

}


public class CoordViewModel
{
    public int Id { get; set; }
    public int X { get; set; }
    public int Y { get; set; }

}
like image 812
Ben Finkel Avatar asked Jul 17 '11 22:07

Ben Finkel


1 Answers

Probably the easiest would be to use a JSON request:

var coord1 = { X: 100, Y: 200 };
var coord2 = { X: 300, Y: 400 };
var zoneData = { 
    Color: '#D8F834', 
    Name: 'new zone', 
    Coords: [ coord1, coord2 ] 
};

$.ajax({
    url: '/Demo/SaveZone',
    type: 'POST',
    contentType: 'application/json; charset=utf-8',
    data: JSON.stringify(zoneData),
    success: function(resp) {
        alert(resp);
    }
});

The JSON.stringify method serializes a javascript object into a JSON string. It is built into modern browsers as a native method. If you want to support legacy browsers that don't have this method you need to include the json2.js script which checks whether the browser natively supports it and if not it provides an implementation.

Now everything should bind properly:

enter image description here

and here's how the successful request will look like:

enter image description here

like image 61
Darin Dimitrov Avatar answered Nov 14 '22 22:11

Darin Dimitrov