假设我有以下内容:
public class Foo
{
public string Value1 { get; set; }
public string Value2 { get; set; }
}
public class BarViewModel
{
public string Baz { get; set; }
public IList<Foo> Foos { get; set; }
}
我的观点是BarViewModel
:
@model BarViewModel
@Html.EditorFor(model => model.Baz)
<table>
@for(int i = 0 ; i < Model.Foos.Count ; i ++)
{
string name1 = "Foos[" + i.ToString() + "].Value1";
string name2 = "Foos[" + i.ToString() + "].Value2";
<tr>
<td>
<input type="text" name="@name1" value="@Model.Foos[i].Value1" />
</td>
<td>
<input type="text" name="@name2" value="@Model.Foos[i].Value2" />
</td>
</tr>
}
</table>
在我的控制器中,我有一个接收BarViewModel
.
给定为 Value1 和 Value2 生成的输入名称是"Foos[0].Value1"
等等"Foos[1].Value1"
,在 POST 方法中,BarViewModel 上的集合由 ModelBinder 自动填充。惊人的。
问题是,如果我在我看来这样做的话:
@for(int i = 0 ; i < Model.Foos.Count ; i ++)
{
<tr>
<td>
@Html.EditorFor(model => model.Foos[i].Value1);
</td>
<td>
@Html.EditorFor(model => model.Foos[i].Value2);
</td>
</tr>
}
然后为输入生成的名称就像这样"Foos__0__Value1"
,并且打破了模型绑定。我的 BarViewModel的Foos
属性,在我的 POST 方法中,现在是null
我错过了什么?
编辑
如果我EditorFor
在集合本身上使用:
@EditorFor(model => model.Foos)
名称生成正确。但这迫使我在 /Views/Share 中构建一个 ViewModel 来处理类型Foos
,这将生成行,我真的不想这样做......
编辑 2
我将在这里澄清我的问题,我知道这有点模糊。
如果我做 :
@EditorFor(model => model.Foos)
输入的名称将具有表单"Foos[0].Value1"
,并且模型绑定在帖子上工作得很好。
但如果我这样做:
@for(int i = 0 ; i < Model.Foos.Count ; i ++)
{
@EditorFor(model => Model.Foos[0].Value1)
}
名称采用形式"Foos__0__Value1"
,模型绑定不起作用。在我的 post 方法中,model.Foos 将为空。
第二种语法破坏模型绑定是否有原因?