我正在尝试使用mongoDB创建一个web api。
这是我的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时如何传递数组。
答案 0 :(得分:1)
编辑:发布Javascript代码。
这是因为您的Post方法接受单个Entity对象而不是Entity实例的列表或数组。您可以按如下方式更改方法。
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);
}
});