我正在尝试用mongoDB创建一个web。
这是我的model
public class Entity
{
[BsonId]
public int Id { get; set; }
public string Name { get; set; }
public string Gender { get; set; }
}这种Post方法
public void Post(Entity entity)
{
var client = new MongoClient("mongodb://localhost:27017");
var server = client.GetServer();
var db = server.GetDatabase("Test");
var collection = db.GetCollection<Entity>("Entities");
collection.Save(entity);
}当我尝试使用单个数据时,它可以工作。
jQuery.ajax({
type: "POST",
datatype: "json",
url: "http://localhost:10746/api/values",
data: { "ID": 1, "Gender": "Male", "Name": "John" },
success: function (data) {
alert(data);
}
});但当我试着做这件事时,它就没用了。
var entities = [
{ "ID": 1, "Gender": "Male", "Name": "John" },
{ "ID": 2, "Gender": "Male", "Name": "Mark" },
{ "ID": 3, "Gender": "Male", "Name": "Tim" },
{ "ID": 4, "Gender": "Male", "Name": "Tom" },
{ "ID": 5, "Gender": "Female", "Name": "Julia" },
{ "ID": 6, "Gender": "Female", "Name": "Joss" }
]
jQuery.ajax({
type: "POST",
datatype: "json",
url: "http://localhost:10746/api/values",
data: entities,
success: function (data) {
alert(data);
}
});我只想知道如何在调用Ajax时传递数组。
发布于 2015-02-15 06:48:41
编辑:张贴Javascript代码。
这是因为Post方法接受的是单个实体对象,而不是实体实例的列表或数组。您可以按以下方式更改该方法。
public void Post(List<Entity> entities)
{
var client = new MongoClient("mongodb://localhost:27017");
var server = client.GetServer();
var db = server.GetDatabase("Test");
foreach(var entity in entities)
{
var collection = db.GetCollection<Entity>("Entities");
collection.Save(entity);
}
}Javascript代码:
var entities = [
{ "ID": 1, "Gender": "Male", "Name": "John" },
{ "ID": 2, "Gender": "Male", "Name": "Mark" },
{ "ID": 3, "Gender": "Male", "Name": "Tim" },
{ "ID": 4, "Gender": "Male", "Name": "Tom" },
{ "ID": 5, "Gender": "Female", "Name": "Julia" },
{ "ID": 6, "Gender": "Female", "Name": "Joss" }
];
var postString = JSON.stringify(entities);
jQuery.ajax({
type: "POST",
datatype: "json",
contentType: 'application/json',
url: "http://localhost:10746/api/values",
data: postString,
success: function (data) {
alert(data);
}
});https://stackoverflow.com/questions/28522722
复制相似问题