【问题标题】:MVC3 collection model binding with EditorForMVC3 集合模型与 EditorFor 的绑定
【发布时间】:2012-01-18 14:57:49
【问题描述】:

关于这个post和这个other one

假设我有以下内容:

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 的 POST 方法。

假设为 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"这会破坏模型绑定。在我的 POST 方法中,我的 BarViewModel 的 Foos 属性现在是 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 将为空。

第二种语法破坏模型绑定是否有原因?

【问题讨论】:

    标签: asp.net-mvc-3 collections razor viewmodel editorfor


    【解决方案1】:

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

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 1970-01-01
      • 2017-04-02
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2011-09-27
      • 1970-01-01
      • 1970-01-01
      相关资源
      最近更新 更多