2

着信 JSON を MVC3 のモデルに変換する方法を示す例を教えてもらえますか?

4

2 に答える 2

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');
    }
});
于 2012-08-16T15:57:21.250 に答える
0

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

さらに追加しますが、サンプルコードもそのフロントページにあります。

于 2012-08-16T15:54:05.107 に答える