0

How can I return to the "previous" view from an action in the controller ?

I have an action that can be reached from 2 different views.

The action can result in 2 ways:

Success - and then I return to 3rd different view Failure - and then I want to return to the previous view (one of the 2) - having the same (old) model data with a TempData["Message"] containing the error.

I want to return to the view that posted to this action - How can I achieve this behavior ?

2 Answers 2

1

You can pass previous view name as a parameter to your action.

public ActionResult Edit(DataObject model, string prevAction)
{
    if (model.IsValid)
    {
        return View("SomeView");
    }
    else
    {
        return RedirectToAction(prevAction, new { data = model });
    }
}
Sign up to request clarification or add additional context in comments.

4 Comments

But need to build the model again before I return the View("LastViewName",Model ?)
You can use RedirectToAction ;)
can't - as this method returns a view (the "success" goes to a new view). I want in case of failure just to return to the previous view, with the previous data....
I Thought that there is an automatic mechanism to go to the previous page - like when validation fails... Your code should work and solve this issue, I will check it and also look a little more about the validation failure scenarios.
0

You could have a query string variable that holds the location to where you would like to return.

Something like controller/action?returnUrl=original/route

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.