简体   繁体   中英

Web forms model binding child collection

I can't figure out how to use model binding to update a child collection like I can in MVC. All the collection-type controls seem to assume some server-side storage mechanism using an edit/update lifecycle, which doesn't fit if this is supposed to be an insert form where I want to store the child collection in the form itself.

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

What can I use in the ??? section here:

<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>

So that I can write an InsertMethod that executes TryUpdateModel, and the child collection populates with the values from ???

I've tried repeaters, gridviews and listviews, and none of them seem to work. This problem doesn't seem to have any answer online [1], but seems like it should be an obvious scenario, and is straightforward in MVC.

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

The only workable solution I could find was to manually call UpdateItem on the nested view for each entry. Basically, the UpdateMethod of the FormView would iterate over the number of items expected, which could also be stored in the form, and then I'd call UpdateItem(index, false) on the nested ListView:

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);
  }
}

This establishes the proper context for the nested ListView's UpdateMethod to be called and everything works as expected. It's a hack, but it works.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM