【问题标题】:How do I get the inserted id (or object) after an insert with the FormView/ObjectDataSource controls?如何在使用 FormView/ObjectDataSource 控件插入后获取插入的 ID(或对象)?
【发布时间】:2010-02-22 15:38:29
【问题描述】:

我有一系列大致符合以下模式的类:

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 事件中切换模式。

这当然行不通。我使用 QueryStringParameter 作为 id 插入时当然不会设置。

所以,我切换到在 ObjectDataSource 的 Selecting 事件期间手动填充 InputParameters。这样做的问题是我需要知道新插入的记录的 id,我找不到一个好的方法来获取。

我知道我可以访问 Insert 方法的返回值,并且在 ItemInserted 事件中输出参数当然我的方法不会使用这些方法中的任何一个返回 id。无论如何,我都无法访问插入完成后插入的 id 或 CustomerInfo 对象。

我能做的最好的事情就是将 CustomerInfo 对象保存在 ObjectDataSource 的 Inserting 事件中。

这感觉是一种奇怪的方法。我认为必须有更好的方法来做到这一点,当我看到它时我会踢自己。有什么想法吗?

【问题讨论】:

    标签: asp.net objectdatasource formview


    【解决方案1】:

    如果您需要检索对象数据源上调用的插入方法的返回值,请使用“Inserted”事件,如下所示:

     protected void ObjDS_Inserted(object sender, ObjectDataSourceStatusEventArgs e)
     {
        int retvalue = Convert.ToInt32(e.ReturnValue);
     }
    

    捕获返回值不需要参数。对于更新方法,使用“更新”

    【讨论】:

    • 我知道我可以在 Inserted 事件中检索到 insert 方法的返回值,但是我的 Insert 方法没有返回 Id。
    猜你喜欢
    • 1970-01-01
    • 2011-06-14
    • 2012-02-05
    • 1970-01-01
    • 2014-12-11
    • 2017-02-06
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多