2012-12-04 11 views
-2

Product 인스턴스를 자바 스크립트로 만들고 [webmethod]을 사용하여 서버에 전달하려고합니다.자바 스크립트에서 객체의 중첩 목록을 만드는 방법

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; } 
} 
내가 Type을 만들 수있는하고

Foo하지만 List<Bar> 자바 스크립트 : 다음

[WebMethod] 
public static void SetProduct(Product product) 
{  
    // i want a product instance  
} 

Product 내가 만들려고 해요 클래스 (이상 코드에 내 의견을 참조 세부 사항)

자바 스크립트

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

_ "나는 데 덮지 않는 무엇 블레 "라고? 질문이 뭐야? – Madbreaks

+0

코드의 내 의견을 참조하십시오. – user829174

답변

0

JavaScript는 List<T>이 무엇인지 알 수 없습니다. 배열을 만드는 방법 만 알고 있습니다. 따라서 Bar 배열을 만들어 JSON에 전달해야합니다.

다행히도 쉽게 수정입니다 :

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

을 위 당신이 필요로하는 모든 아마입니다. 나는 ASP.NET이 자동적으로 List<Bar>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" }); 
관련 문제