我无法弄清楚如何在MVC中使用模型绑定来更新子集合。所有集合类型控件似乎都假设使用编辑/更新生命周期的一些服务器端存储机制,如果这应该是一个插入表单,我想将子集合存储在表单本身中。 / p>
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
答案 0 :(得分:0)
我能找到的唯一可行解决方案是手动在每个条目的嵌套视图上调用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建立了正确的上下文,并且一切都按预期工作。这是一个黑客,但它的确有效。