简体   繁体   中英

After insert redirect to edit page. Unable to get ID

I have FormView in Category_New.aspx from where new item is inserted. It is inserted in following method.

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

I would like to redirect a user to the page that is for editing that Item. That page is Category_Edit.aspx.

How to get ID of inserted item in method myForm_ItemInserted so that the following code would work?

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

How to know the ID of inserted item?

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.

If you are using entity framework, It will persist save object auto generated id at the time data inserted to the database.

Normally entity framework execute SELECT SCOPE_IDENTITY() to get when auto-generated Ids.

Therefore you should be able to get inserted id as following.

int Id= item.ID; 

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM