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!
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; }
}
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:
and here's how the successful request will look like:
My guess:
public List<CoordViewModel> Coords { get; set; }
(I admit this is a shot in the dark)
精彩评论