2014-07-10 17 views
2

客戶端代碼:南希使用JSON複雜的對象,現在工作

var basket = { 
      products: [], 
      user: { name: "schugh" } 
     }; 

    $("#basket table tr").each(function (index, item) { 
     var product = $(item).data('product'); 
     if (product) { 
      basket.products.push(product); 
     } 

    }); 

    $.ajax({ 
     url: "http://localhost:12116/basketrequest/1", 
     async: true, 
     cache: false, 
     type: 'POST', 
     data: JSON.stringify(basket), 
     contentType: 'application/json; charset=utf-8', 
     dataType: 'json', 

     success: function (result) { 
      alert(result); 
     }, 
     error: function (jqXHR, exception) { 
      alert(exception); 
     } 
    }); 

Server代碼:

Post["/basketrequest/{id}"] = parameters => 
{  
    var basketRequest = this.Bind(); //basketrequest is null 
    return Response.AsJson(basketRequest , HttpStatusCode.OK); 
}; 

其他模型類:

[Serializable] 
public class BasketRequest 
{ 
    public User User; 
    public List<Product> Products; 
} 

public class Product 
{ 
    public int Id { get; set; } 
    public string Name { get; set; } 
    public string Category { get; set; } 
    public decimal Price { get; set; } 
    public ProductStatus ProductStatus { get; set; } 
} 

public enum ProductStatus 
{ 
    Created, 
    CheckedBy, 
    Published 
} 

public class User 
{ 
    public string Name { get; set; } 
} 

在南希模塊this.Bind();返回的代碼null。如果我將複雜對象更改爲List<Product>,即沒有包裝BasketRequest,則該對象很好...

任何指針?

編輯:JSON發佈:

{ 
    "User": { 
    "Name": "SChugh" 
    }, 
    "Products": [{ 
    "Id": 1, 
    "Name": "Tomato Soup", 
    "Category": "Groceries", 
    "Price": 1 
    }, { 
    "Id": 2, 
    "Name": "Yo-yo", 
    "Category": "Toys", 
    "Price": 3.75 
    }] 
} 
+0

你能後的JSON,你嘗試過泛型方法'this.Bind ()' – jjchiw

+0

{ 「用戶「:{」Name「:」SChugh「}, 」Products「:[{」Id「:1,」Name「:」Tomato Soup「,」Category「:」Groceries「,」Price「 「Id」:2,「Name」:「Yo-yo」,「Category」:「Toys」,「Price」:3.75}] } – chugh97

+0

@jjchiw我也試過小寫, !我卡住了! – chugh97

回答

8

BasketRequest對象應該實現的屬性,而不是字段。所以

public class BasketRequest 
{ 
    public User User { get; set; } 
    public List<Product> Products { get; set; } 
} 

你也應該使用泛型方法太

this.Bind<BasketRequest>();