【问题标题】:Web forms model binding child collectionWeb 表单模型绑定子集合
【发布时间】:2016-04-22 23:13:51
【问题描述】:

我不知道如何像在 MVC 中那样使用模型绑定来更新子集合。所有集合类型的控件似乎都假设一些使用编辑/更新生命周期的服务器端存储机制,如果这应该是我想将子集合存储在表单本身中的插入表单,则不适合。

public class BarViewModel
{
  public string Name {get;set;}
}
public class FooViewModel
{
  public string Description {get;set;}
  public List<BarViewModel> Bars {get;set;}
}

我可以在 ???这里的部分:

<asp:FormView ID="Entry" RenderOuterTable="false" runat="server" DefaultMode="Insert"
   ItemType="FooViewModel" SelectMethod="Entry_GetItem" InsertMethod="Entry_InsertItem">
   <InsertItemTemplate>
     <asp:TextBox ID="txtDescription" Text="<%# BindItem.Description %>" runat="server" />
     <!-- ??? -->
   </InsertItemTemplate>
</asp:FormView>

这样我就可以编写一个执行 TryUpdateModel 的 InsertMethod,并且子集合会填充来自???的值

我尝试过中继器、网格视图和列表视图,但它们似乎都不起作用。这个问题网上好像没有任何答案[1],但是好像应该是一个明显的场景,在MVC中很直接。

[1]ASP.NET Web Forms 4.5 model binding where the model contains a collection

【问题讨论】:

    标签: c# asp.net webforms model-binding asp.net-4.5


    【解决方案1】:

    我能找到的唯一可行的解​​决方案是手动在每个条目的嵌套视图上调用 UpdateItem。基本上,FormView 的 UpdateMethod 将遍历预期的项目数,这些项目也可以存储在表单中,然后我会在嵌套的 ListView 上调用 UpdateItem(index, false):

    FooViewModel foo;
    BarViewModel bar;
    
    public void Foo_UpdateItem([Control("BarCount")] int? barCount)
    {
      TryUpdateItem(foo);
      var bars = (ListView)Entry.FindControl("FooBars");
      for (var i = 0; i < barCount; ++i)
      {
          bar = foo.Bars[i];
          bars.UpdateItem(i, false);
      }
    }
    

    这为要调用的嵌套 ListView 的 UpdateMethod 建立了正确的上下文,并且一切都按预期工作。这是一个 hack,但它有效。

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 1970-01-01
      • 2014-03-07
      • 2016-08-03
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      相关资源
      最近更新 更多