2012-12-04 103 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" }); 
相關問題