Obtain View name in Controller, ASP.NET MVC
I am using asp.net mvc. I have 4 pages that show list of events(different type of events) and "Details" link on each page leads to "EventDescription.aspx" View.开发者_如何学C
The "EventDescription.aspx" has a link called "Back to Events" which has to take the user to the appropriate page.
Eg: if the "Details" request came from page1 the "Back to Events" link needs to point to page1.aspx. Same for page2.aspx,page3.aspx,page4.aspx.
My plan is to capture the view name (page1.aspx) in controller action "EventDescription" and store in ViewData before displaying the "EventDescription.aspx" and user the ViewData value for "Back to Events" link.
How to obtain the name of the View from where the request comes from inside a Action?
Thank in advance.
When you render the page, you also need to render a link that will point to the correct page when Back to Events is clicked. This is best set up in the controller method, where you readily have access to all of the necessary information.
An easy way to do this is to put the return link information in a ViewData variable
(untested pseudocode follows). In your controller method:
ViewData["ReturnPath"] = "/Content/Page/1";
And then in your view:
<% =Html.ActionLink("Back To Events", ViewData["ReturnPath"]) %>
or something similar.
Alternatively, you could try something like
ViewContext.RouteData.Values["action"]
...if you don't mind the magic string there. This will give you the calling action.
if you just want to get the Url where you came from you can do this in your Action
ViewData["ReturnPath"] = this.Request.UrlReferrer.AbsolutePath;
This give you the Url of the page where you came from. If your from Page1 then you go to EventDescription. In your EventDescription Action, your ReturnPath ViewData has the Url of Page1. Or Vice Versa.
I suggest you use TempData instead of ViewData. For instance you could have a setting like this.
public ActionResult Details(int id)
{
var event = repository.GetByID(id);
if (event != null)
{
TempData["ReturnPath"] = Request.UrlReferrer.ToString();
return View(event);
}
else { //....... ; }
}
And in your View you could have a regular ActionLink like so
<% =Html.ActionLink("Back To Events", TempData["ReturnPath"]) %>
If you want to be DRY, you could also create an Action method in your controller just to handle the redirects like so.
public ActionResult GoBack()
{
return Redirect(TempData["ReturnPath"]);
}
And in your View a normal ActionLink like so
<% =Html.ActionLink("Back To Events", "GoBack") %>
Put the return path in TempData (not ViewData) and it can pass from the calling page to the Details page. See also http://jonkruger.com/blog/2009/04/06/aspnet-mvc-pass-parameters-when-redirecting-from-one-action-to-another/
精彩评论