几年前有人问过这个问题,但我发现寻找相同的答案。这对我有用。在 ASPX 中,这是遵循所述模型的完整 GridView:
<asp:EntityDataSource ID="dsResidents" runat="server"
ConnectionString="name=connString"
DefaultContainerName="dbContext"
EntitySetName="Residents"
Include="Building"
EnableUpdate="true" />
<asp:GridView ID="ResidentGrid" runat="server"
DataSourceID="dsResidents"
OnRowUpdating="ResidentsGrid_RowUpdating"
AutoGenerateColumns="False">
<Columns>
<asp:CommandField ShowEditButton="True" />
<asp:TemplateField Visible="false">
<ItemTemplate>
<asp:Label ID="lblID"
Text='<%# Eval("residentId") %>'
runat="server" />
</ItemTemplate>
</asp:TemplateField>
<asp:TemplateField HeaderText="Name">
<ItemTemplate>
<asp:Label ID="lblName"
Text='<%# Eval("residentName") %>'
runat="server" />
</ItemTemplate>
<asp:TemplateField HeaderText="CountryCode">
<ItemTemplate>
<asp:Label ID="lblCountryCode"
Text='<%# Eval("Building.number") %>'
runat="server" />
</ItemTemplate>
<EditItemTemplate>
<asp:EntityDataSource ID="dsBuildings" runat="server"
ConnectionString="name=connString"
DefaultContainerName="dbContext"
EntitySetName="Buildings" />
<asp:DropDownList ID="ddlBuilding"
DataSourceID="dsBuildings"
DataTextField="number"
DataValueField="id"
SelectedValue='<%# Eval("id") %>' <!-- I am not sure about this line -->
runat="server" />
</EditItemTemplate>
</asp:TemplateField>
</Columns>
</asp:GridView>
请注意,如果您使用向导创建实体模型,默认情况下,ConnectionString 名称与 DefaultContainerName 相同。在支持类中添加用于更新网格行的事件处理程序 (OnRowUpdating):
protected void ResidentsGrid_RowUpdating(object sender, GridViewUpdateEventArgs e)
{
// This is for retrieving the entity object for the resident selected
Label idLabel = (Label)ResidentsGrid.Rows[e.RowIndex].Cells[1].FindControl("lblID");
int residentId = int.Parse(idLabel.Text);
// And this is for the building selected in the dropdown
DropDownList ddl = (DropDownList)ResidentsGrid.Rows[e.RowIndex].Cells[4].FindControl("ddlBuilding");
// I would like to say that the cell index is the column position but as I know it isn't
using (dbContext ctx = new dbContext())
{
Resident resident = ctx.Residents
.Where(res => res.residentId == residentId).First();
Building selectedBuilding = ctx.Buildings
.Where(bld => bld.id == ddl.SelectedItem.Value).First();
resident.Building = selectedBuilding;
ctx.SaveChanges();
}
}