C# 为什么在EditorTemplate中呈现集合时会得到错误的表单元素名称?
在我当前的项目中,我有几个视图模型实例,其中包含一系列子视图模型,如下所示:C# 为什么在EditorTemplate中呈现集合时会得到错误的表单元素名称?,c#,asp.net-mvc-3,C#,Asp.net Mvc 3,在我当前的项目中,我有几个视图模型实例,其中包含一系列子视图模型,如下所示: public class ParentViewModel { public ParentViewModel() { Children = new List<ChildViewModel>(); } public List<ChildViewModel> Children { get; set; } } public class ChildVie
public class ParentViewModel
{
public ParentViewModel()
{
Children = new List<ChildViewModel>();
}
public List<ChildViewModel> Children { get; set; }
}
public class ChildViewModel
{
public string Name { get; set; }
public int Age { get; set; }
}
EditorFor将自动迭代集合,并将EditorTemplate应用于每个单独的项。我遇到的问题是,如果我希望对每三个项执行某些操作,将两个项呈现到同一个表行中,或者其他一些变体,我需要强制EditorFor使用特定的EditorTemplate,这很好,但出现了一个奇怪的问题
这是我的测试编辑器模板
@model List<Sandbox.Models.ChildViewModel>
<table>
@for(int i = 0, j = 1; i < Model.Count - 1; i+=2)
{
<tr>
<td>
@Html.TextBoxFor(o => o[i].Age)
</td>
@if(j < Model.Count)
{
<td>
@Html.TextBoxFor(o => o[j].Age)
</td>
}
</tr>
}
</table>
@model Sandbox.Models.ChildViewModel
<tr>
<td>
@Html.TextBoxFor(o => o.Name)
</td>
<td>
@Html.TextBoxFor(o => o.Age)
</td>
</tr>
而是
Children.[1].Age
这将使模型绑定器完全失控,并且它将拒绝在表单提交时重新填充父视图模型
我能够解决这个问题的唯一方法是将EditorTemplate的模型设置为父视图模型,而不是子视图模型列表,这严重限制了我使用模板的能力,因为我可能有多个位置具有相同的子视图模型集合,我没有包含它的相同父模型
在这一点上,我知道以下选项:
感谢您的帮助 您几乎可以像这样更改代码 包含EditorFor调用的视图
@model Sandbox.Models.ParentViewModel
<html>
<head>
<title>title</title>
</head>
<body>
<div>
@using(Html.BeginForm()) {
@Html.EditorFor(o => o.Children, "ChildrenTemplate")
<input type="submit" />
}
</div>
</body>
</html>
<table>
@for (int i = 0; i < Model.Children.Count; i++)
{
@Html.EditorFor(o => o.Children[i]) //also you could mention the template name
}
</table>
@for(int i=0;io.Children[i])//您还可以提到模板名称
}
这是我的测试编辑器模板
@model List<Sandbox.Models.ChildViewModel>
<table>
@for(int i = 0, j = 1; i < Model.Count - 1; i+=2)
{
<tr>
<td>
@Html.TextBoxFor(o => o[i].Age)
</td>
@if(j < Model.Count)
{
<td>
@Html.TextBoxFor(o => o[j].Age)
</td>
}
</tr>
}
</table>
@model Sandbox.Models.ChildViewModel
<tr>
<td>
@Html.TextBoxFor(o => o.Name)
</td>
<td>
@Html.TextBoxFor(o => o.Age)
</td>
</tr>
@model Sandbox.Models.ChildViewModel
@Html.TextBoxFor(o=>o.Name)
@Html.TextBoxFor(o=>o.Age)
欲知详情
http://blog.stevensanderson.com/2010/01/28/editing-a-variable-length-list-aspnet-mvc-2-style/在您的
ChildrenTemplate.cshtml中:
@model List<Sandbox.Models.ChildViewModel>
<table>
@Html.EditorForModel()
</table>
@model Sandbox.Models.ChildViewModel
<tr>
<td>
@Html.TextBoxFor(x => x.Name)
</td>
<td>
@Html.TextBoxFor(x => x.Age)
</td>
</tr>
这样,您就不需要在代码中编写任何循环,也不必担心输入字段的名称错误。它按惯例运作