2012-08-16 70 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