Web forms model binding child collection

℡╲_俬逩灬. 提交于 2019-12-24 15:36:52

问题


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


回答1:


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.



来源:https://stackoverflow.com/questions/36804682/web-forms-model-binding-child-collection

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!