2012-12-04 107 views
-2

我试图在Javascript中创建Product实例,而不是使用[webmethod]将它传递到服务器。如何在javascript中创建对象的嵌套列表

[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; } 
} 

我能够创建TypeFoo但不List<Bar>在Javascript:(见我的意见的代码更详细信息)

的Javascript

function setProduct() { 
    var product = {}; 
    product.Type = {}; 
    product.Foo = {}; 

    product.Type.ID = 'typeID'; 
    product.Foo.ID = 'fooID'; 
    product.Foo.Color = 'fooColor'; 

    //here is my question how can create List<Bar> Bars and add it to product item??? 

    $.ajax({ 
     type: "POST", 
     url: "Default.aspx/SetProduct", 
     contentType: "application/json; charset=utf-8", 
     dataType: "json", 
     async: false, 
     data: "{product:" + JSON.stringify(product) + "}", 
    }); 
} 
+2

什么_“我有特鲁ble“_是什么意思?你有什么问题? – Madbreaks

+0

请在代码中查看我的意见 – user829174

回答

0

JavaScript不知道List<T>是什么。它只知道如何制作数组。所以你必须构建一个Bar的数组,然后在JSON中传递它。

幸运的是,这是一个简单的办法:

product.Bars = [ 
    { Name: "bar 1" }, 
    { Name: "bar 2" }, 
    { Name: "bar 3" }, 
]; 

以上可能是你所需要的。我敢肯定,ASP.NET将是足够聪明到Bar[]转换成List<Bar>自动的,但以防万一它不是:

public class Product 
{ 
    public Type Type { get; set; } 
    public Foo Foo { get; set; } 
    public IEnumerable<Bar> Bars { get; set; } 
} 

然后,如果你仍然想List<T>功能,只是转换数组在你的WebMethod列表:

[WebMethod] 
public static void SetProduct(Product product) 
{  
    var list = product.Bars.ToList(); 
    product.Bars = list; 
    return product; 
} 

现在,你仍然可以访问那些漂亮List<T>方法:

((List<Bar>)product).Add(new Bar() { Name = "bar 4" }); 
0
// create an array 
product.Bars = []; 

// add an element to the array 
product.Bars.push({ 
    Name: "Foo" 
}); 

或者你可以初始化元素的数组,以及:

// create and initialize array 
product.Bars = [{Name:"Foo"}, {Name:"Bar"}]; 
0

使用数组,并与array.push添加项目到阵列。例如:

product.Bars = []; 
product.Bars.push({ Name: "foo" }); 
相关问题