在html.beginform中传递嵌套的viewmodel

时间:2011-05-12 13:59:25

标签: asp.net-mvc razor viewmodel

我遇到的问题是我有一个带有嵌套viewmodel(ChildViewModel)的viewmodel(MasterViewModel),我在表单中有一个下拉列表,通过jQuery执行ajax发布以更新部分视图。但无论我做什么,Part动作中的childviewmodel总是空的,我不明白为什么。下面是一个简化的代码示例:

控制器:

Namespace MvcApplication2
    Public Class TestController
        Inherits System.Web.Mvc.Controller

        '
        ' GET: /Test

        Function Index() As ActionResult
            Dim viewModel As New MasterViewModel
            viewModel.MyId = 123
            viewModel.ChildViewModel = New ChildViewModel With {.Name = "woohoo"}
            viewModel.Items = New List(Of SelectListItem) From { _
                New SelectListItem With {.Text = "first", .Value = "1"},
                New SelectListItem With {.Text = "second", .Value = "2"}
            }
            viewModel.SelectedItem = New List(Of SelectListItem) From { _
                New SelectListItem With {.Text = "first", .Value = "1"}
            }
            Return View(viewModel)
        End Function

        Function Part(ByVal viewModel As ChildViewModel) As ActionResult
            viewModel.Name = viewModel.Name & "_"
            Return PartialView(viewModel)
        End Function


    End Class
End Namespace

索引视图:

@ModelType MvcApplication2.MasterViewModel
@Code
    ViewData("Title") = "Index"
End Code
<script type="text/javascript" language="javascript">
    function update() {
        $('#myForm').change(function () {
            var form = $('#myForm');
            $.ajax({
                url: form.attr('action'),
                type: form.attr('method'),
                data: form.serialize(),
                success: function (result) {
                    $('#mjoo').html(result);
                }
            });
        });
    }

</script>
<h2>Index</h2>

<p>@Model.MyId</p>

@Using Html.BeginForm("Part", "Test", FormMethod.Post, New With {.id = "myForm"})

    @Html.DropDownListFor(Function(x) x.SelectedItem, Model.Items, New With {.onchange = "update()"})
    @Html.HiddenFor(Function(x) x.ChildViewModel)

End Using

<div id="mjoo">

    @Html.Partial("Part", Model.ChildViewModel)

</div>

部分视图:

@ModelType MvcApplication2.ChildViewModel

<p>@Model.Name</p>

的ViewModels:

Public Class MasterViewModel
    Property ChildViewModel As ChildViewModel
    Property Items As List(Of SelectListItem)
    Property SelectedItem As List(Of SelectListItem)
    Property MyId As Integer
End Class

Public Class ChildViewModel
    Property Name As String
End Class

这可能有什么问题。我知道有些东西我不见了,但我看不到它。

1 个答案:

答案 0 :(得分:0)

你无法将整个模型神奇地填充到一个字段中 您需要为模型中的每个属性创建一个单独的隐藏字段。

我建议将整个表单移动到一个单独的局部视图中,该视图使子模型简化代码。