具有IEnumerable属性的Form上的FormView

时间:2013-05-30 05:09:34

标签: c# asp.net .net data-binding .net-4.5

人员视图模型:

public class Person {
    public string Name { get; set; }
    public List<Person> Relatives { get; set; }
    public bool IsSelected { get; set; }
}

我的页面上有一个asp:FormView控件,其中包含一个asp:GridView,它绑定到我Person类的集合属性。

<asp:FormView ID="ui_frmMain" runat="server" DefaultMode="Edit" OnCallingDataMethods="ui_frmMain_CallingDataMethods" SelectMethod="GetItems" UpdateMethod="UpdateItems" ItemType="Person">
    <EditItemTemplate>
        <%# Item.Name %>
        <asp:GridView ID="..." runat="server" DataSource='<%# Bind("Relatives") %>' ItemType="Person">
             <ItemTemplate>
                        <asp:TemplateField>
                            <ItemTemplate>
                                <asp:CheckBox ID="Selected" runat="server" Checked='<%# Bind("IsSelected") %>' />
                            </ItemTemplate>
                        </asp:TemplateField>
             </ItemTemplate>
        </asp:GridView>
    <EditItemTemplate>
</asp:FormView>

我正在使用.Net 4.5数据绑定将我的模型发送回UpdateMethod UpdateItems(Person person)但是Relatives属性始终为null。

有办法:

  • 从gridview双向绑定
  • 将gridview的CheckBox绑定到模型上的IsSelected属性

1 个答案:

答案 0 :(得分:0)

在更新的人员对象上保存更改之前,“手动”循环并逐个添加嵌套的集合对象。

例如:

UpdateItems(Person person)
{
   // :( probably null for Relatives :(
   GridView myGrid = (GridView)FindControl("MyGrid");
   for (int i = 0; i < myGrid.Rows.Count; i++)
   {
       Textbox txtName = (Textbox)myGrid.Rows[i].FindControl("");
       CheckBox chkSelected = (Checkbox)myGrid.Rows[i].FindControl("");
       Person p = new Person();
       p.Name = txtName.Text;
       p.IsSelected = chkSelected.cheked;
       person.Relatives.Add(p);
    }
    myEntity.SaveChanges();

这种方法很糟糕,但我还没有看到任何可以识别嵌套集合中的变化的东西。

相关问题