Asp.net 如何在使用FormView/ObjectDataSource控件进行插入后获取插入的id(或对象)?
我有一系列类松散地符合以下模式:Asp.net 如何在使用FormView/ObjectDataSource控件进行插入后获取插入的id(或对象)?,asp.net,objectdatasource,formview,Asp.net,Objectdatasource,Formview,我有一系列类松散地符合以下模式: public class CustomerInfo { public int Id {get; set;} public string Name {get; set;} } public class CustomerTable { public bool Insert(CustomerInfo info) { /*...*/ } public bool Update(CustomerInfo info) { /*...*/ }
public class CustomerInfo {
public int Id {get; set;}
public string Name {get; set;}
}
public class CustomerTable {
public bool Insert(CustomerInfo info) { /*...*/ }
public bool Update(CustomerInfo info) { /*...*/ }
public CustomerInfo Get(int id) { /*...*/ }
/*...*/
}
成功插入后,insert方法将设置传入的CustomerInfo对象的Id属性。我已经在几个地方使用过这些类,并且更愿意修改它们。
现在我正在尝试编写一个ASP.NET页面来插入和更新记录。
我目前正在使用ObjectDataSource和FormView控件:
<asp:ObjectDataSource
TypeName="CustomerTable"
DataObjectTypeName="CustomerInfo"
InsertMethod="Insert"
UpdateMethod="Update"
SelectMethod="Get"
/>
我可以成功插入和更新记录。成功插入后,我想将FormView的模式从插入切换到编辑。
我的第一次尝试是在ItemInserted事件中切换模式
这当然行不通。我对id使用了QueryStringParameter,插入时当然没有设置它
因此,我切换到在ObjectDataSource的Selecting事件期间手动填充InputParameters。问题是我需要知道新插入的记录的id,我找不到一个好方法来获取它
我知道我可以访问Insert方法的返回值,并在itemserted事件中输出参数。当然,我的方法不会使用任何这些方法返回id。我找不到任何方法来访问插入完成后插入的id或CustomerInfo对象
我所能做的最好的事情就是在ObjectDataSource的插入事件中保存CustomerInfo对象
这样做感觉很奇怪。我想一定有更好的方法来做这件事,当我看到它的时候,我会踢自己。有什么想法吗?如果需要检索objectdatasource上调用的insert方法的返回值,请使用“Inserted”事件,如下所示:
protected void ObjDS_Inserted(object sender, ObjectDataSourceStatusEventArgs e)
{
int retvalue = Convert.ToInt32(e.ReturnValue);
}
捕获返回值不需要任何参数。对于Update方法,请使用“Updated”我知道我可以在insert事件中检索insert方法的返回值,但我的insert方法不返回Id。