2009-06-08 74 views
2

我有一個ObjectDataSource,我綁定到一個DetailsView控件。我有插入方法寫在業務層(調用到數據層),一切工作正常..直到我想在插入方法觸發前做其他事情。在進入我的業務層之前,我需要訪問文件上傳控件。因此,我在DetailsView上連接了一個ItemCommand事件 - 它提取事件,我可以用FileUpload控件完成所需的事情。在這種情況下,我在業務層中調用insert方法 - 與ObjectDataSource控件中指定的方法相同。但是Insert方法觸發兩次!經過一分鐘的思考,我意識到這是預期的行爲 - 從ItemCommand事件調用一次,第二次從ObjectDataSource的InsertMethod觸發。ObjectDataSource插入方法

我想我可以簡單地從ObjectDataSource控件刪除InsertMethod屬性來消除該方法的雙火,但是當我這樣做,我得到這個錯誤:

Inserting is not supported by ObjectDataSource 'objStudentDetails' unless the InsertMethod is specified.

那麼,有什麼辦法,我可以告訴ObjectDataSource不會觸發該方法?請參閱下面的代碼簡化代碼:

<asp:DetailsView ID="dtvStudentDetails" 
    runat="server" 
    AutoGenerateRows="False" 
    DataSourceID="objStudentDetails" 
    OnItemCommand="dtvStudentDetails_ItemCommand"> 
    : 
    : 
</asp:DetailsView> 


<asp:ObjectDataSource ID="objStudentDetails" 
    runat="server" 
    TypeName="AIMLibrary.BLL.Students" 
    SelectMethod="GetStudentDetails" 
    UpdateMethod="UpdateStudent">   
    : 
    : 
</asp:ObjectDataSource> 


public static Int32 InsertStudent(Int32 studentId, String firstName, String lastName, String employer, String phone, String email, String address, String city, String state, String zip, String dob, String cardImagePath) 
{ 
    StudentDetails record = new StudentDetails(firstName, lastName, employer, phone, email, address, city, state, zip, dob, cardImagePath); 
    StudentsProvider provider = new StudentsProvider(); 
    return provider.InsertStudent(record); //actual insert happens in here.. 
} 

回答

5

是否有一個原因,你不能只是在ObjectDataSource上處理插入事件?它甚至有辦法取消插入,如果你想。就在插入前

<asp:ObjectDataSource id=CustomerObjectDataSource" runat="server" 
    oninserting="CustomerObjectDataSource_Inserting" 
</asp:ObjectDataSource> 

此事件,如果你需要從傳播阻止它,你可以這樣做:

就在事件處理程序添加到ObjectDataSource的標記(或使用設計器)像這樣:

protected void CustomerObjectDataSource_Inserting(object sender, ObjectDataSourceMethodEventArgs e) 
{ 
    InsertMethod(someParams); 

    //If you are satisfied with what has already been done.. 
    e.Cancel = true;  
} 
+0

很好用!不知道我是如何錯過的 - 謝謝! – Tone 2009-06-08 03:17:06