2012-08-16 72 views

回答

3

這已經由框架爲您處理了。

所以你定義模型:

public class MyViewModel 
{ 
    public int Id { get; set; } 
    public string Name { get; set; } 
    public Complex Complex { get; set; } 
    public IEnumerable<Foo> Foos { get; set; } 
} 

public class Complex 
{ 
    public int Id { get; set; } 
} 

public class Foo 
{ 
    public string Bar { get; set; } 
} 

然後控制器動作採取這種模式:

[HttpPost] 
public ActionResult SomeAction(MyViewModel model) 
{ 
    ... 
} 

最後你錘JSON請求匹配您的視圖模型的結構此控制器操作:

$.ajax({ 
    url: '@Url.Action("SomeAction")', 
    type: 'POST', 
    contentType: 'application/json', 
    data: JSON.stringify({ 
     id: 1, 
     name: 'john smith of course, why asking?', 
     complex: { 
      id: 3 
     }, 
     foos: [ 
      { bar: 'the bar' }, 
      { bar: 'the baz' }, 
     ] 
    }), 
    success: function(result) { 
     alert('hooray'); 
    } 
}); 
+0

我們決定製作web服務SOAP。不需要JSON。 – MB34 2012-08-17 20:40:38

0

http://james.newtonking.com/projects/json-net.aspx

我將增加更多,但示例代碼也是頭版。

+0

我不想將我的模型轉換爲JSON,我想將JSON轉換爲我的模型。我看不到那個包。 – MB34 2012-08-16 15:56:28

+0

您可以反序列化JSON,然後將數據映射到您的模型 – darethas 2012-08-16 15:58:31

+0

爲什麼當框架已經爲您處理這個問題時,您會做所有的事情? – 2012-08-16 15:59:34