开发者

store multiple id's from first aspx page to next aspx page

开发者 https://www.devze.com 2023-01-03 16:53 出处:网络
i have my first aspx page that has data thatthe user fills in. it is in format of textbox\'s and at the end of it all the user clicks submit and all data goes in the database. In the database each rec

i have my first aspx page that has data thatthe user fills in. it is in format of textbox's and at the end of it all the user clicks submit and all data goes in the database. In the database each record gets an ID field. Now when the users clicks submit and goes to the n开发者_JAVA技巧ext page, i want the ID's (they could be 1 to 1000+) from the DB that he just inserted and have them available on the second page. how can i take all the id's from page 1 to page 2? can i do it in session? or something else. Please put some sample code so i can understand better.


First create some sort of sessionId and store it in the session object.

Session["SessionId"] = Guid.NewGuid().ToString();

When storing the id's, in the db, also record the SessionId(above) with it, so you'll know all the records for that session.

Then in the next page, just do a query to get all id's related to that SessionId


It can be done, and it's not so hard. In a nutshell, here's what you will want to do:

  • for each item you insert into the database, return the newly created item's id
  • store the saved item's id in your database methods someplace easy to access - Session is a good place.
  • on the next page, you can access your Session variable to retrieve the id's you saved.

(Currently editing post to add code)

The best and safest way to return newly inserted ID's is through transactions (plus, if there is a problem with the insert, you can roll it back). Here's how a transaction would look where we do an insert and return an ID:

ALTER PROCEDURE [dbo].[storeFrontItems]
    @itemName NVARCHAR(255),                    
    @itemDescription NVARCHAR(255),

    @newItemID INT OUTPUT
AS

    BEGIN TRANSACTION   
    INSERT INTO storeFrontItems (Name, Description) VALUES (@itemName, @itemDescription)
    SET @error = @@ERROR
    IF @error <> 0
     BEGIN
      ROLLBACK TRANSACTION
      RETURN @error
     END
    ELSE
     BEGIN
      SELECT @newItemID = @@IDENTITY
     END 
     COMMIT TRANSACTION


    RETURN

Then you can store your new ID in a session variable

  Dim newlyCreatedItemID int
  newlyCreatedItemID = databaseInsertNewItem /* ... */

  /* to store it in a session variable */
  Session("NewItemID") = newlyCreatedItemID

  /* to retrieve it from a session variable */
  newlyCreatedItemID = i = CType(Session("NewItemID"), newlyCreatedItemID )
0

精彩评论

暂无评论...
验证码 换一张
取 消

关注公众号