Bhushan Shah
Bhushan Shah

Reputation: 1038

How do I go back to the previous view through a hyperlink in ASP.NET MVC?

I have models (POCO entities) like Student, Course, Standard etc. I have corresponding controllers such as StudentController etc. I have a view Index for each model which displays the list of all the corresponding entities in DB. For example, StudentController.Index() returns the /Student/Index view. However, if there are no Student records in the DB, instead of returning the Index view , I redirect to the Empty action method of the Navigation controller, i.e. NavigationController.Empty(), which returns the /Navigation/Empty view. This is done for all model entity classes.

Now, on the empty page, I wish to have a hyperlink to go back to the previous page. So I created an action method called GoBack() in the NavigationController class, in which I redirect to the previous view. But how can I access the information about what the previous page was in this action method? Or is there a better way to do this? I do not want to use the back button.

Upvotes: 0

Views: 1505

Answers (1)

Aage
Aage

Reputation: 6252

As far as I'm concerned there are a couple of routes to take here. You could use sessions or the application cache to store a las visited page, and then get that page (by storing a route for instance) in the GoBack() action using a RedirectToAction.

But maybe a nicer and stateless aproach would be to render the hyperlink by having a view model having two properties for last used controller & action. Then you could pass these from the action result calling the /Navigation/Empty action (when there aren't any records).

ViewModel

public class NavigationVM
{
public string LastAction {get;set;}
public string LastController {get;set;}
}

Navigation Controller Action

public ActionResult Empty(string lastAction, string lastController)
{
var vm = new NavigationVM()
{
LastAction = lastAction,
LastController = lastController
}
return View(vm);
}

View

@model = Namespace.NavigationVM

@Html.ActionLink("LinkName", Model.LastAction, Model.LastController)

EDIT

If you then need to find out from where the students controller was called (in your example) you can go about this the same way. I.e.: Render the link to the StudentsController with extra route values.

StudentController:

public ActionResult Index(string lastAction, string lastController)

{
     .... // no students
return RedirectToAction("Empty", "Navigation", new RouteValueDictionary(new { lastAction = "Index", lastController= "Student"}));

}

View with hyperlink to students controller (use the action and controller that rendered this view as lastAction and lastController respectively):

@Html.ActionLink("Get students", "Index", "Student", new { lastAction= "Index", lastController = "CallingController" }, null)

Upvotes: 1

Related Questions