I have a page which displays data from multiple tables in a one-to-many relationship via various FormViews and ListViews. A ListView is nested within a FormView and the correct data displays but, when I go to update, the last record in the ListView updates all rows within the ListView with its contents and I can't figure out why.
Here is some of the code:
<asp:FormView runat="server" ItemType="Table1"
DefaultMode="Edit" DataKeyNames="Table1_key"
SelectMethod="GetAll" OnItemCommand="ItemCommand"
UpdateMethod="UpdateTables" RenderOuterTable="false">
<EmptyDataTemplate>
Cannot find the Episode with Episode key <%: FriendlyUrl.Segments[0] %>
</EmptyDataTemplate>
<EditItemTemplate>
<asp:DynamicControl Mode="Edit" DataField="foo1" runat="server"/>
<asp:Button runat="server" ID="UpdateButton" CommandName="Update" Text="Update" CssClass="btn btn-primary" />
</EditItemTemplate>
<asp:ListView ID="ListView1" runat="server"
DataKeyNames="Table2_key" SelectMethod="GetTable2"
ItemType="Table2">
<ItemTemplate>
<tr>
<td>
//this doesn't update properly
<asp:DynamicControl runat="server" DataField="foo" ID="foo" Mode="Edit" />
</td>
</tr>
</ItemTemplate>
</asp:ListView>
</asp:FormView>
Update method in code-behind (which works for updating the FormView (i.e. Table1) but not the ListView content (Table2):
public void UpdateTables(int Table1_key)
{
using (_db)
{
var item = _db.Table1.Find(Table1_key);
if (item == null)
{
// The item wasn't found
ModelState.AddModelError("", String.Format("Item with id {0} was not found", Table1_key));
return;
}
TryUpdateModel(item); // this updates the foo1 property
if (ModelState.IsValid)
{
_db.SaveChanges();
}
var lesions = _db.Table2.Where(cl => cl.Table1_key == Table1_key);
foreach (var lesion in lesions)
{
TryUpdateModel(lesion); //this updates ALL the children with the value I put in the last textbox.
}
_db.SaveChanges();
}
}
I can't find anything to sort this but surely someone has wanted to do the same as me, i.e. display data from multiple tables but only have one update button for everything? Thanks!