插入重定向到编辑页面后。无法获取ID

时间:2016-04-15 11:37:41

标签: c# asp.net webforms insert formview

我在Category_New.aspx中有FormView,其中插入了新项目。它按以下方法插入。

 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?

2 个答案:

答案 0 :(得分:1)

What you probably can do is to have a global int type variable to hold the value of new category Id, then you can pass it in in your redirect method.

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}));            
}

The key here is that when inserting, the generated ID is saved into the instance of the object being saved.

答案 1 :(得分:1)

如果您正在使用实体框架,它将在插入数据库的数据时保留对象自动生成的id。

通常实体框架执行SELECT SCOPE_IDENTITY()以获取自动生成的ID。

因此,您应该能够获得插入ID,如下所示。

int Id= item.ID;