简体   繁体   English

ASP.NET MVC - 表单提交,检索数据库ID和重定向

[英]ASP.NET MVC - Form Submission, Retrieve Database ID, and Redirect

I currently learning ASP.NET MVC . 我目前正在学习ASP.NET MVC。 I wondered if it is possible when a form is submitted to the get the id of the new record and then redirect to a new page with the new record id? 我想知道是否有可能将表单提交到获取新记录的ID然后重定向到具有新记录ID的新页面?

The information is entered into the database correctly, but I'm not sure how to get the id? 信息正确输入数据库,但我不知道如何获取ID?

For example, complete a new customer details form and then redirect the page to an orders form where new orders can be added for the customer. 例如,填写新的客户详细信息表单,然后将页面重定向到订单表单,以便为客户添加新订单。

How are you accessing the database? 你是如何访问数据库的? If you are using an ORM (such as NHibernate or LINQ to SQL) then the object should have it's ID property updated after you insert it into the database. 如果您正在使用ORM(例如NHibernate或LINQ to SQL),那么在将对象插入数据库后,该对象应该更新它的ID属性。

If you are hand rolling the SQL then you need to do a select in the same statement as the insert of: 如果您正在手动滚动SQL,那么您需要在与插入相同的语句中执行select:

insert into ...

select scope_identity()

This will return the ID of the row you have just created. 这将返回刚刚创建的行的ID。

Then you can do this within your action: 然后你可以在你的行动中做到这一点:

return RedirectToAction("YourActionName", new {id});

With the ID retrieved either from the saved object or the return value of the SQL. 使用从保存的对象或SQL的返回值中检索的ID。 Whichever fits your scenario. 适合您的情况。

Edit 编辑

As you've mentioned you are using NHibernate then you can do this: 正如您所提到的,您正在使用NHibernate,那么您可以这样做:

var myNewObject = // some way of creating the object

// some way of saving the object 
// at this point NHibernate will have set the ID of the object for you

return RedirectToAction("YourActionName", new { id = myNewObject.Id });

One question from me: What do you use for the DB layer? 我提出的一个问题:你对数据库层使用了什么? That will tell us how to better answer your question. 这将告诉我们如何更好地回答您的问题。

For the redirect, once you have your ID you could use: 对于重定向,一旦有了ID,就可以使用:

return Redirect(string url); OR RedirectToAction(string actionPath)

where url is a combination of path and your new id. 其中url是路径和新ID的组合。

Write your query so that it will return the id of the new record and redirect the user with the new id. 编写您的查询,以便它返回新记录的ID并使用新ID重定向用户。 For eg if you are using SQL Server and manually writing your queries: 例如,如果您使用SQL Server并手动编写查询:

command.CommandText = "Insert Into Customers(...) Values (...) Select @@Identity";
long id = long.Parse(command.ExecuteScalar().ToString());
Redirect("...customers/neworders/" + id);

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

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