ViewModel里面的ViewModel - 如何让它发布?

时间:2014-08-29 15:48:07

标签: c# asp.net-mvc asp.net-mvc-viewmodel editorfor

我在另一个viewmodel中有一个viewmodel用于分离关注点。我为它创建了一个编辑器模板,并在运行时在控制器中设置默认值。不幸的是,当父视图模型发布到控制器时,它不会保存子视图模型的项的值。这是代码:

注意:某些代码名称已更改,因此如果存在任何不一致,请在评论中指出。我已经过了大约4倍,并且发现了我认为的全部内容。

public class ParentViewModel {
    public ChildViewModel {get;set;}
}
public class ChildViewModel {
    public List<Item> Items {get;set;}
}
public class Item {
    public int Id {get;set;
    public string Name {get;set;}
}

我创建了一个在视图上正确绑定的EditorTemplate

@model MyProject.ViewModels.ChildViewModel

@foreach (var item in Model.Items)
{
    <div class="Item" @String.Format("id=Item{0}", @item.Id) >
        Item #@Html.DisplayFor(models => item.Id): 
        @Html.LabelFor(model => item.Name)
        @Html.EditorFor(model => item.Name)
    </div>   
}

但是,当我提交ParentViewModel绑定的表单时,ChildViewModel的项目为空!

Controller.cs

public class ControllerController{
    public ActionResult Form {
        return View(new ParentViewModel {
            ChildViewModel = new ChildViewModel {
                Items = new List<Item>(Enumerable.Range(1,20).Select(i => new Item { Id=i })
            }
        });
    }
    [HttpPost]
    [ActionName("Form")]
    public class ActionResult FormSubmitted(ParentViewModel parentViewModel) {
        //parentViewModel.ChildViewModel.Items is null!
        _fieldThatIsRepresentingMyDataService.Save(parentViewModel);
    }
}

ViewView.cshtml

 <div class="editor-label">
     @Html.LabelFor(model => model.ChildViewModel)
</div>
<div id="ItemList" class="editor-field">
    @Html.EditorFor(model => model.ChildViewModel)
</div>

非常感谢任何帮助。

1 个答案:

答案 0 :(得分:2)

问题不在于嵌套视图模型,而是模型绑定与表单和数组一起使用的方式。

您需要确保您的表单项呈现如下:

<input type="text" name="people[0].FirstName" value="George" />
<input type="text" name="people[0].LastName" value="Washington" />
<input type="text" name="people[1].FirstName" value="Abraham" />
<input type="text" name="people[1].LastName" value="Lincoln" />
<input type="text" name="people[3].FirstName" value="Thomas" />
<input type="text" name="people[3].LastName" value="Jefferson" />

关键部分是输入name属性中的数组索引。如果没有索引部分,模型绑定将不会填充您的列表。

要渲染它,你需要一个for循环:

@for (int i = 0; i < Model.Items.Length; i++) {
 ...
  @Html.EditorFor(m => Model.Items[i].Name)
 ...
}

查看Phil Haack的post详细讨论它。

相关问题