I have a basic form that allows a user to create an Employee
. Once the user selects the submit
button, the page should be redirected
to a summary page. This summary page needs to show the details that were added on the Employee
form.
For example, I have a form that looks like this:
Once the user selects Submit
, it should then redirect the user to the following page:
The issue that I'm running into is getting that redirect url. My url looks something like: http://www.localhost.com/Employee/1234/ The
1234
represents theEmployee
id. How can I pull thatEmployee Id
?
My Current HTML
<button type="submit" name="saveButton" id="saveBtn" class="btn btn-primary">Submit</button>
Please note that I am using .NET, so am open to using
Razor Syntax.
Update on Story
After reading all of your comments, I went and dug deeper into my problem. This is what I found.
There is a RouteConfig.cs
file with the following route:
routes.MapRoute(
name: "ListEmployee",
url: "Employee/{employeeId}",
defaults: new { controller = "Employee", action = "List"},
constraints: new {employeeId = "\\d+"}
)
Because I have this route, I decided to modify this controller method to utilize it:
[HttpPost]
public ActionResult AddEmployee(ViewModel<EmployeeModel> model)
{
// logic here
return RedirectToAction("ListEmployee", new { employeeId = model.Body.Employee.Id, fromEmployeeProject = true });
}
Issue: This completely crashes. Stating:
No route in the route table matches the supplied values.
Any ideas on what I am doing wrong?
If you're using Entity Framework (EF), it follows up each INSERT
statement with SCOPE_IDENTITY()
when auto-generated ids are used.
SCOPE_IDENTITY returns the last identity value inserted into an identity column in the same scope. (MSDN)
As such, if your Employee
ID is an auto-generated column in the database, you should be able to get the ID right after saving your changes:
[HttpPost]
public ActionResult Add(Employee employee)
{
using (var context = new MyContext())
{
// add the employee object
context.Employees.Add(employee);
// save changes
context.SaveChanges();
// the id will be available here
int employeeId = employee.Id;
// ..so perform your Redirect to the appropriate action, _
// and pass employee.Id as a parameter to the action
return RedirectToAction("Index", "Employee", new { id = employeeId });
}
}
Obviously you haven't provided us with your controller and action names so make sure that you replace them with the appropriate values.
Collected from the Internet
Please contact [email protected] to delete if infringement.
Comments