I have an ObjectDataSource that I'm binding to a DetailsView control. I have the insert method written in a business layer (which calls down into a data layer) and everything works fine.. until i want to do something else before the insert method fires. Before going to my business layer I need access to a fileupload control. So I wired up an ItemCommand event on the DetailsView - it picks up the event and I can do what i need with the FileUpload control just fine. In that event I call the insert method in the business layer - the same method specified in the ObjectDataSource control. But the Insert method fires twice! After thinking on this for a minute i realize this is the expected behavior - it's fired once when called from the ItemCommand event, and the second time from ObjectDataSource InsertMethod.
I thought I could simply remove the InsertMethod attribute from the ObjectDataSource to eliminate the double fire on that method, but when I do that I get this error:
Inserting is not supported by ObjectDataSource 'objStudentDetails' unless the InsertMethod is specified.
So is there any way I can tell the ObjectDataSource not to fire the method? See code simplified code below:
<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..
}
Is there a reason you can't just handle the Inserting event on the ObjectDataSource? It even has a way to cancel the insert if you want.
Just add the event handler to the ObjectDataSource in markup (or use the designer):
<asp:ObjectDataSource id=CustomerObjectDataSource" runat="server"
oninserting="CustomerObjectDataSource_Inserting"
</asp:ObjectDataSource>
This event fires just before the insert, and if you need to stop it from propagating, you can do something like this:
protected void CustomerObjectDataSource_Inserting(object sender, ObjectDataSourceMethodEventArgs e)
{
InsertMethod(someParams);
//If you are satisfied with what has already been done..
e.Cancel = true;
}