tags:

views:

250

answers:

3

I currently learning 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?

The information is entered into the database correctly, but I’m not sure how to get the 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.

A: 

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:

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

where url is a combination of path and your new id.

NTulip
Thanks, but how do I get the id. I'm using nhibernate.
A: 

Write your query so that it will return the id of the new record and redirect the user with the new id. For e.g. if you are using SQL Server and manually writing your queries:

command.CommandText = "Insert Into Customers(...) Values (...) Select @@Identity";
long id = long.Parse(command.ExecuteScalar().ToString());
Redirect("...customers/neworders/" + id);
Serhat Özgel
Don't use @@IDENTITY. I would recommend SCOPE_IDENTITY() (SQL Server)
NTulip
Thanks, I don't think the above will work as I'm using Nhibernate.
@NTulip I did not know about that. Please feel free to edit the answer and provide a better advice.
Serhat Özgel
+4  A: 

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.

If you are hand rolling the SQL then you need to do a select in the same statement as the insert of:

insert into ...

select scope_identity()

This will return the ID of the row you have just created.

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. Whichever fits your scenario.

Edit

As you've mentioned you are using NHibernate then you can do this:

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 });
Garry Shutler
Thanks, its working now.