1

ネストされたビューモデル構造があります:

public class PersonViewModel
{
    public int Height { get; set; }
    public List<LegViewModel> Legs {get;set;}
}

public class LegViewModel
{
    public int Length { get; set; }
}

jquery post を使用して、これに JSON を送信します。

<script>
    $(function () {

        $("#mybutton").click(function () {
            $.ajax({
                type: "POST",
                data: {
                    Height: 23,
                    Legs: [
                        {
                            Length: 45,
                        }
                    ]
                }
            });
        });
    });
</script>
<button id="mybutton">hello world!</button>

このコントローラーアクションに投稿しています:

[HttpPost]
public ActionResult Save(PersonViewModel model)
{
    return Json(new { success = true });
}

リスト内の要素のHeightと同様に、 a の値PersonViewModelが入力されますが、リスト内の各要素は入力されません。配列に45の要素が 1 つ含まれると予想される場合、プロパティは 0 のままです。LegsLegViewModelLengthLegsLength

これは、リストをまったく使用しない場合も同じであることに注意してくださいPersonViewModel.Legs property, but still as the

// view model
public class PersonViewModel
{
    public int Height { get; set; }
    //public List<LegViewModel> Legs {get;set;}
    public LegViewModel Leg { get; set; }
}

public class LegViewModel
{
    public int Length { get; set; }
}

// view
$("#mybutton").click(function () {
    $.ajax({
        type: "POST",
        data: {
            Height: 23,
            Leg: 
                {
                    Length: 45,
                }

        }
    });
})

JSON を使用してネストされたビュー モデルを設定するにはどうすればよいですか? 私が見逃したものはありますか、それとも MVC でこれを行うことはできませんか?

4

1 に答える 1

1

データを送信するときに MVC Model Binder がコレクションを適切に解析するように$.ajaxするには、次の 2 つのことを行う必要があります。

  • contentTypeに設定'application/json'
  • そして、dataJSONを保持する必要があるためJSON.stringify、データ

したがって、モデルバインダーによって解析できる正しい使用法は次のとおりです。

$("#mybutton").click(function () {
        $.ajax({
            type: "POST",
            contentType: 'application/json',
            data: JSON.stringify({
                Height: 23,
                Legs: [
                    {
                        Length: 45,
                    }
                ]
            })
        });
    });
于 2013-01-29T20:21:36.190 に答える