2012-01-31 49 views
2

假設我有兩個班,一個來自EntityObject衍生和其他從第一得出:是否可以爲具有子類的實體對象設置可編輯的DetailsView?

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

在ASP.NET頁面中,用戶在列表(GridView)選擇一個小發明和小發明的詳細信息然後呈現在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不再支持更新數據。一個工作的「編輯」按鈕(使編輯用戶界面出現)在那裏,但在編輯之後單擊「更新」根本不會執行任何操作。

有沒有妥善解決這個困境?

+0

嘛[此MSDN文章(HTTP:// MSDN .microsoft.com/en-us/library/system.web.ui.webcontrols.entitydatasource.commandtext.aspx)解釋了「CommandText」部分:「當分配CommandText屬性時,更新,插入和刪除功能是禁用」。嗯... – jadarnel27 2012-01-31 14:30:17

回答

1

我解決了這個使用下面的技巧:

  • 不要指定數據源,這使得DetailsView無法自動更新數據上CommandText,但更新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.

相關問題