Skip to content Skip to sidebar Skip to footer

Redirect Url After Form Submission

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 s

Solution 1:

One of the most common way of doing it is to return different View from your Action that you call from Employee Form. For instance let say your Employee Forms calls EmployeeController->Add(Employee employee) action

Inside of your Employee Action you will have something like this:

[HttpPost]
public ActionResult Add(Employee employee)
{
    // process request and create new employee in repositoryreturn View("Summary");
}

Another way of doing it is to call RedirectToAction(), this is similar to Response.Redirect() in ASP.NET WebForms.

[HttpPost]
public ActionResult Add(Employee employee)
{
    // process request and create new employee in repositoryreturn RedirectToAction("Summary");
}

You can allso call Redirect method. This will cause the browser to receive 302 error and redirect to your controller/action specified

[HttpPost]
public ActionResult Add(Employee employee)
{
    // process request and create new employee in repositoryreturn Redirect("YourController/Summary");
}

Solution 2:

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 hereint 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.

Solution 3:

To get the id you can, in your view, add an input type hidden:

<inputtype="hidden" name="id" value="[value]" />

in your controller:

[HttpPost]
public ActionResult [ActionName] (int id)
{
.....
employeeRepository.Save(employee);
return RedirectToAction("Summary", new {id});
}

and in your action Summary:

public ActionResult Summary(int id){
.....
}

Post a Comment for "Redirect Url After Form Submission"