ObjectDataSource插入方法

时间:2009-06-08 00:50:31

标签: asp.net objectdatasource

我有一个ObjectDataSource,我绑定到DetailsView控件。我有一个在业务层(调用数据层)中编写的插入方法,一切正常......直到我想在插入方法触发之前做其他事情。在进入我的业务层之前,我需要访问fileupload控件。所以我在DetailsView上连接了一个ItemCommand事件 - 它接收了事件,我可以用FileUpload控件做我需要的就好了。在那种情况下,我在业务层中调用insert方法 - 与ObjectDataSource控件中指定的方法相同。但是Insert方法会触发两次!在考虑了这一点后,我意识到这是预期的行为 - 它从ItemCommand事件调用时被触发一次,而第二次从ObjectDataSource InsertMethod触发。

我以为我可以简单地从ObjectDataSource中删除InsertMethod属性以消除该方法的双重攻击,但是当我这样做时,我收到此错误:

  

不支持插入   ObjectDataSource'objStudentDetails'   除非指定了InsertMethod。

那么有什么办法可以告诉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..
}

1 个答案:

答案 0 :(得分:5)

是否有理由不能只处理ObjectDataSource上的Inserting事件?如果你愿意,它甚至可以取消插入。

只需将事件处理程序添加到标记中的ObjectDataSource(或使用设计器):

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

此事件在插入之前触发,如果您需要阻止它传播,您可以执行以下操作:

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

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