【问题标题】:Is it possible to have an editable DetailsView for entity objects with subclasses?是否可以为具有子类的实体对象提供可编辑的 DetailsView?
【发布时间】:2012-01-31 14:12:34
【问题描述】:

假设我有两个类,一个派生自EntityObject,另一个派生自第一个:

public class Gizmo : EntityObject { ... }
public class SpecialGizmo : Gizmo { ... }

在 ASP.NET 页面中,用户在列表中选择一个 Gizmo(GridView),然后 Gizmo 的详细信息将显示在 DetailsView 中。目标是让用户能够查看和编辑详细信息。

这里是相关的DetailsView 及其关联的EntityDataSource

<asp:DetailsView ID="GizmosDetailsView" DataSourceID="dsGizmoDetails"
    AutoGenerateEditButton="True" AutoGenerateInsertButton="True"
    AutoGenerateRows="False" DataKeyNames="GizmoId" runat="server">
    <Fields>
        <asp:BoundField DataField="GizmoId" HeaderText="GizmoId" ReadOnly="True" SortExpression="GizmoId" />
        <asp:BoundField DataField="Description" HeaderText="Description" SortExpression="Description" />
        <!-- ... etc. --->
    </Fields>
</asp:DetailsView>

<asp:EntityDataSource ID="dsGizmoDetails" runat="server" ConnectionString="[...]"
    DefaultContainerName="[...]" EnableFlattening="False" EnableUpdate="True"
    Where="it.[GizmoId] = @GizmoId">
    <WhereParameters>
        <asp:ControlParameter ControlID="gvwGizmos" Name="GizmoId" PropertyName="SelectedValue" Type="Int64" />
    </WhereParameters>
</asp:EntityDataSource>

上述失败,但有以下异常:

InvalidOperationException:必须定义 CommandText 或 EntitySetName。

这是可以理解的。但是,提出的两个选项都破坏了一些东西:

  • 如果我添加EntitySetName="Gizmo",则只会显示实际类型为Gizmo 的实体。如果选择了SpecialGizmo,DetailsView 将显示为空白。

  • 如果我添加CommandText(或Select)属性,则DetailsView 不再支持更新数据。有一个有效的“编辑”按钮(使编辑 UI 出现),但在进行编辑后单击“更新”根本没有任何作用。

这个困境有合适的解决方案吗?

【问题讨论】:

  • 那么this MSDN article 解释了CommandText 部分:“分配CommandText 属性时,更新、插入和删除功能被禁用”。嗯...

标签: asp.net detailsview


【解决方案1】:

我使用以下 hack 解决了这个问题:

  • 请在数据源上指定CommandText,这样DetailsView无法自动更新数据,但更新UI仍然可用。

  • DetailsViewOnItemUpdating 事件设置为如下所示:

    protected void GizmoDetailsView_Updating(object sender,
            DetailsViewUpdateEventArgs e)
    {
        db.ExecuteStoreCommand(/* use e.Keys["GizmoId"] and e.NewValues */);
        db.SaveChanges();
    
        // manually set the DetailsView back to read-only mode
        GizmoDetailsView.ChangeMode(DetailsViewMode.ReadOnly);
    
        // need to cancel the event, as otherwise we get the following exception:
        // InvalidOperationException: Update is disabled for this control.
        e.Cancel = true;
    }
    

此解决方案的缺点: other controls on the page that rely on the data which is thusly updated, do not refresh until a manual page reload by the user.

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 2018-04-13
    • 1970-01-01
    • 2012-10-16
    • 2021-07-22
    • 1970-01-01
    • 1970-01-01
    • 2016-05-22
    • 1970-01-01
    相关资源
    最近更新 更多