简体   繁体   中英

how to get the last accessed action in asp.net mvc

How can I get the last accessed 'Action' in a asp.net mvc app.

Example I have a menuItem called 'Add to Favourites" when clicked is navigated to a page in which I need to populate a textbox with this url

There is no built in mechanism to do this. What I would do, is populate your Add To Favourites url, like so:

Create an extension method to encode the current url:

public static class UrlHelperExtensions
{
    public static string AddToFavourites(this UrlHelper helper)
    {
        return helper.RouteUrl("AddToFavourites", new { url = EncodeUrl() });
    }

    private static string EncodeUrl()
    {
        var request = HttpContext.Current.Request;
        string url = request.Url.ToString();

        return Convert.ToBase64String(Encoding.Default.GetBytes(url));
    }
}

Then wire up your action:

public ActionResult AddToFavourites(string url)
{
    url = Encoding.Default.GetString(Convert.FromBase64String(url));

    return View(url);
}

Make sure you have a route:

routes.MapRoute(
    "AddToFavourites",
    "Home/AddToFavourites/{url}", new { url = (string)null });

And then you can use the helper in your menu:

<a href="<%= Url.AddToFavourites() %>">Add To Favourites</a>

Hope that helps?

覆盖基础控制器OnActionExecuted并在其中保存操作(例如在Session中)。

I don't think it's an asp.net MVC question. Here your "Action" refers an URL right? You can use JavaScript document.referrer to get the last visited URL.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM