[英]After insert redirect to edit page. Unable to get ID
I have FormView in Category_New.aspx from where new item is inserted. 我从插入新项目的Category_New.aspx中有FormView。 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.
该页面是Category_Edit.aspx。
How to get ID of inserted item in method myForm_ItemInserted so that the following code would work? 如何在方法myForm_ItemInserted中获取插入项的ID,以便以下代码可以工作?
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? 如何知道插入物品的ID?
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. 您可能要做的是拥有一个全局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}));
}
The key here is that when inserting, the generated ID is saved into the instance of the object being saved. 这里的关键是插入时,生成的ID将保存到要保存的对象的实例中。
If you are using entity framework, It will persist save object auto generated id at the time data inserted to the database. 如果您使用的是实体框架,它将在数据插入数据库时持久保存对象自动生成的ID。
Normally entity framework execute SELECT SCOPE_IDENTITY() to get when auto-generated Ids. 通常,实体框架执行SELECT SCOPE_IDENTITY()以获得自动生成的ID。
Therefore you should be able to get inserted id as following. 因此,您应该能够按以下方式获取ID。
int Id= item.ID;
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.