如何在javascript中创建对象的嵌套列表
我正在尝试用Javascript创建如何在javascript中创建对象的嵌套列表,javascript,asp.net,Javascript,Asp.net,我正在尝试用Javascript创建产品实例,然后使用[webmethod]将其传递给服务器 [WebMethod] public static void SetProduct(Product product) { // i want a product instance } 下面是我试图创建的Product类: public class Product { public Type Type { get; set; } public Foo Foo {
产品
实例,然后使用[webmethod]
将其传递给服务器
[WebMethod]
public static void SetProduct(Product product)
{
// i want a product instance
}
下面是我试图创建的Product
类:
public class Product
{
public Type Type { get; set; }
public Foo Foo { get; set; }
public List<Bar> Bars { get; set; }
}
public class Type
{
public string ID { get; set; }
}
public class Foo
{
public string ID { get; set; }
public string Color { get; set; }
}
public class Bar
{
public string Name { get; set; }
}
或者,也可以使用元素初始化数组:
// create and initialize array
product.Bars = [{Name:"Foo"}, {Name:"Bar"}];
使用数组,并使用
array.push将项目添加到数组中。例如:
product.Bars = [];
product.Bars.push({ Name: "foo" });
JavaScript不知道什么是列表。它只知道如何制作数组。因此,您必须构造一个Bar
s数组,并将其传递到JSON中
幸运的是,这是一个简单的解决方案:
product.Bars = [
{ Name: "bar 1" },
{ Name: "bar 2" },
{ Name: "bar 3" },
];
以上可能就是您所需要的全部。我很确定ASP.NET将足够智能,可以自动将条[]
转换为列表,但以防万一:
public class Product
{
public Type Type { get; set; }
public Foo Foo { get; set; }
public IEnumerable<Bar> Bars { get; set; }
}
现在您仍然可以访问那些漂亮的列表方法:
((List<Bar>)product).Add(new Bar() { Name = "bar 4" });
((列表)产品).Add(新条(){Name=“Bar 4”});
什么叫“我有麻烦”?你的问题是什么?请看我在代码中的注释
public class Product
{
public Type Type { get; set; }
public Foo Foo { get; set; }
public IEnumerable<Bar> Bars { get; set; }
}
[WebMethod]
public static void SetProduct(Product product)
{
var list = product.Bars.ToList();
product.Bars = list;
return product;
}
((List<Bar>)product).Add(new Bar() { Name = "bar 4" });