2016-04-15 111 views
1

我有FormView在Category_New.aspx從哪裏插入新項目。它被插入以下方法。插入重定向到編輯頁面後。無法獲得ID

public void myForm_InsertItem() 
    {    
     var item = new A.Models.Category(); 
     CategoryContext db = new CategoryContext();    
     TryUpdateModel(item); 
     if (ModelState.IsValid) 
     { 
      // Save changes here 
      db.Category.Add(item); 
      db.SaveChanges(); 
      //item.CategoryID is present from this point 
     } 
    } 

我想將用戶重定向到用於編輯該項目的頁面。該頁面是Category_Edit.aspx。

如何獲取方法myForm_ItemInserted中插入項的ID,以便下面的代碼可以工作?

protected void myForm_ItemInserted(object sender, FormViewInsertedEventArgs e) 
{ 
    Response.RedirectToRoute(GetRouteUrl("CategoryEdit", new {CategoryID = /* how to get ID of inserted item??? */}));    
} 

如何知道插入物品的ID?

+0

http://stackoverflow.com/questions/5212751/how-can-i-get-id-of-inserted-entity-in-entity-framework – Emanuele

+0

@Emanuelle但該項目變量是來自方法不可訪問myForm_ItemInserted? – Willmore

+0

首先第一種方法是ItemInserting。在一個事件中移動代碼。或者將item變量移出ItemInserting方法 – Emanuele

回答

1

你可能會做的是有一個全局的int類型變量來保存新的類別ID的值,然後你可以在你的重定向方法中傳遞它。

private int newCategoryId; 
public void myForm_InsertItem() 
    {    
     var item = new A.Models.Category(); 
     CategoryContext db = new CategoryContext();    
     TryUpdateModel(item); 
     if (ModelState.IsValid) 
     { 
      // Save changes here 
      db.Category.Add(item); 
      db.SaveChanges(); 
      //item.CategoryID is present from this point 
      newCategoryId = item.CategoryId; // presumably it's called categoryId 
     } 
    } 

protected void myForm_ItemInserted(object sender, FormViewInsertedEventArgs e) 
{ 
    Response.RedirectToRoute(GetRouteUrl("CategoryEdit", new {CategoryID = newCategoryId}));    
} 

這裏的關鍵是插入時,生成的ID被保存到被保存對象的實例中。

+0

我正在考慮把分類會議。然後在方法myForm_ItemInserted從會話中檢索categoryid,重定向,從會話中清除類別id。我只是想知道在插入後,webforms中重定向到編輯的便捷方式是什麼。 – Willmore

+0

@Willmore如果你不喜歡使用Session,那麼你可以考慮ViewState,它允許你通過回發來保存值。這樣你可以在你的重定向方法中傳遞這個值。或者,使用HiddenField控件可以是另一種選擇。 – woodykiddy

1

如果您使用的是實體框架,它會在數據插入到數據庫時持久保存對象自動生成的id。

通常實體框架執行SELECT SCOPE_IDENTITY()以獲取自動生成的Ids。

因此,您應該能夠獲得如下所示的插入ID。

int Id= item.ID; 
+0

ID可用:)。只是不知道如何訪問myForm_ItemInserted方法中的item變量。你怎麼做呢? – Willmore

+1

在類級別定義一個變量,如下所示。然後將該變量用於ItemInserted方法。 Int categoryId = 0; public void myForm_InsertItem() { //數據插入代碼。 } 保護無效myForm_ItemInserted(對象發件人,FormViewInsertedEventArgs E) { Response.RedirectToRoute(GetRouteUrl( 「CategoryEdit」,新的{類別ID =的categoryId})); } –