Warning: file_get_contents(/data/phpspider/zhask/data//catemap/6/asp.net-mvc-3/4.json): failed to open stream: No such file or directory in /data/phpspider/zhask/libs/function.php on line 167

Warning: Invalid argument supplied for foreach() in /data/phpspider/zhask/libs/tag.function.php on line 1116

Notice: Undefined index: in /data/phpspider/zhask/libs/function.php on line 180

Warning: array_chunk() expects parameter 1 to be array, null given in /data/phpspider/zhask/libs/function.php on line 181
Asp.net mvc 3 MVC3集合模型与EditorFor绑定_Asp.net Mvc 3_Collections_Razor_Viewmodel_Editorfor - Fatal编程技术网

Asp.net mvc 3 MVC3集合模型与EditorFor绑定

Asp.net mvc 3 MVC3集合模型与EditorFor绑定,asp.net-mvc-3,collections,razor,viewmodel,editorfor,Asp.net Mvc 3,Collections,Razor,Viewmodel,Editorfor,关于这个和这个 假设我有以下几点: 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; } } 在我的控制器中,我有一个POST方法,可以接

关于这个和这个

假设我有以下几点:

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; }
}
在我的控制器中,我有一个POST方法,可以接收
BarViewModel

假设为Value1和Value2生成的输入名称是
“Foos[0].Value1”
“Foos[1].Value1”
等,则ModelBinder会自动填充POST方法中BarViewModel上的集合。太棒了

问题是,在我看来,如果我这样做:

   @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>
   }
名称生成正确。但这迫使我在/Views/Share中构建一个ViewModel来处理类型
Foos
,它将生成行,我并不想这样做

编辑2
我会在这里澄清我的问题,我知道这有点含糊不清

如果我这样做:

@EditorFor(model => model.Foos)
输入的名称将采用格式
“Foos[0].Value1”
,并且模型绑定在POST上运行良好

但如果我这样做:

@for(int i = 0 ; i < Model.Foos.Count ; i ++)
{
    @EditorFor(model => Model.Foos[0].Value1)
}
for(int i=0;imodel.Foos[0].Value1) } 名称的形式为“Foos\uuuu 0\uuuu Value1”,模型绑定不起作用。在我的post方法中,model.Foos将为null


第二种语法破坏模型绑定有什么原因吗?

我不完全确定您的问题到底是什么。然而,MVC就是这样工作的。EditorFor使用EditorTemplates,您可以为您的类型定义一个编辑器模板。它不必在共享中使用,它可以在您使用的任何级别中使用。例如,您可以在/Views/Home/EditorTemplates/Foos.cshtml上使用它,只要您不在除主控制器以外的任何地方使用它

@EditorFor(model => model.Foos)
@for(int i = 0 ; i < Model.Foos.Count ; i ++)
{
    @EditorFor(model => Model.Foos[0].Value1)
}