简而言之,使用 for 循环而不是 foreach 循环(请参阅此处的答案)。您需要手动索引它
MVC Razor 视图嵌套 foreach 的模型
编辑:添加示例代码
@for(int i=0; i < Model.ListTwo.Count; i++)
{
@Html.HiddenFor(t => t.ListTwo[i].Id)
}
好的,对于从 ICollection 继承的集合,请尝试
@for (int i = 0; i < Model.CollectionThree.Count; i++)
{
@Html.Hidden("CollectionThree[" + i + "].Id", Model.CollectionThree.ElementAt(i).Id)
}
另一个编辑:为避免使用属性名称,您可以执行类似的操作
@for (int i = 0; i < Model.CollectionThree.Count; i++)
{
@Html.Hidden(Html.NameFor(t => Model.CollectionThree) + "[" + i + "]." +
Html.NameFor(t =>Model.CollectionThree.ElementAt(i).Id)
,Model.CollectionThree.ElementAt(i).Id )
}
它不优雅,但它没有硬编码属性名称。
然后让这些人脱离循环
@{
var collectionname = Html.NameFor(t => Model.CollectionThree);
var propname = Html.NameFor(t => Model.CollectionThree.First().Id);
}
@for (int i = 0; i < Model.CollectionThree.Count; i++)
{
@Html.Hidden( collectionname+ "[" + i + "]." + propname ,Model.CollectionThree.ElementAt(i).Id )
}
我很抱歉没有早点回复。我退出了,因为我还有其他事情要做。您可能还想进行空检查,即,如果 count > 0,则分配 propname,否则跳过整个事情