我在另一个视图模型中有一个视图模型,用于分离关注点。我为它创建了一个编辑器模板,并在运行时在控制器中设置默认值。不幸的是,当父视图模型向控制器发布时,它不会保存子视图模型项的值。以下是代码:
注意:一些代码名被更改了,所以如果有任何不一致之处,请在注释中指出。我已经翻了四遍,找到了所有我想的东西。
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的项为null!
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>任何帮助都是非常感谢的。
发布于 2014-08-29 16:07:02
问题不在于嵌套视图模型,而在于模型绑定与窗体和数组的工作方式。
您需要确保表单项呈现如下:
<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)
...
}看看菲尔哈克的这个帖子,它详细地讨论了it。
https://stackoverflow.com/questions/25571778
复制相似问题