2011-11-02 90 views
0

爲什麼3級別的嵌套模型綁定json的工作?ASP.NET MVC 3 Json模型綁定3級對象

測試2級,比如在LevelTwo上添加一個字符串屬性,但3個級別不起作用?這是由設計,錯誤,還是我錯過了什麼?

客戶端jQuery的崗位:

$.ajax({ 
     url: "MyController/MyAction", 
     dataType: "json", 
     type: "POST", 
     cache: false, 
     data: { 
      Level1: { 
       Level2: { 
        StringValue: "Test" 
       } 
      } 
     } 
    }); 

服務器端模式:

public class MyForm 
{ 
    public LevelOne Level1 { get; set; } 
} 

public class LevelOne 
{ 
    public LevelTwo Level2 { get; set; } 
} 

public class LevelTwo 
{ 
    public string StringValue { get; set; } 
} 

回答

1

爲什麼犯規3級嵌套模型從JSON工作結合

您沒有發送任何JSON到服務器。如果您要發送一個JSON請求方法如下:

$.ajax({ 
    url: "MyController/MyAction", 
    contentType: 'application/json; charset=utf-8', 
    dataType: "json", 
    type: "POST", 
    cache: false, 
    data: JSON.stringify({ 
     Level1: { 
      Level2: { 
       StringValue: "Test" 
      } 
     } 
    }) 
}); 

JSON.stringify方法就是序列化的JavaScript文字到JSON字符串。它本地建立在現代瀏覽器中。如果您需要支持舊版瀏覽器,則可以將json2.js腳本添加到您的網頁中。

+0

Doh!謝謝!我認爲dataType:「json」是所有需要的。你知道,假設是所有人的母親...... – MatteS

+0

@MatteS,'dataType:'json''指示響應內容類型,而不是請求。另外,如果你的服務器發送了適當的Content-Type響應頭到application/json,你甚至不需要它,因爲jQuery會自動推斷它。你可以從你的ajax請求中省略這個參數。 –

+0

是的。這讓我回想起爲什麼在我們的代碼庫中添加了dataType選項,值得注意的是它添加了頭文件「Accept:application/json,text/javascript,*/*;」到請求,這就是我們的錯誤處理邏輯喜歡的東西。 – MatteS