如何重定向到ASP中的前一个操作。净MVC吗?

时间:2022-10-30 08:27:25

Lets suppose that I have some pages

假设我有一些页面

  • some.web/articles/details/5
  • some.web /文章/细节/ 5
  • some.web/users/info/bob
  • some.web /用户/信息/鲍勃
  • some.web/foo/bar/7
  • some.web / foo / bar / 7

that can call a common utility controller like

这可以调用一个通用的实用程序控制器。

locale/change/es or authorization/login

地区/改变/ es或授权/登录

How do I get these methods (change, login) to redirect to the previous actions (details, info, bar) while passing the previous parameters to them (5, bob, 7)?

如何让这些方法(更改、登录)重定向到以前的操作(详细信息、信息、栏),同时将以前的参数传递给它们(5、bob、7)?

In short: How do I redirect to the page that I just visited after performing an action in another controller?

简而言之:如何在另一个控制器中执行操作后重定向到刚才访问的页面?

9 个解决方案

#1


127  

try:

试一试:

public ActionResult MyNextAction()
{
    return Redirect(Request.UrlReferrer.ToString());
}

alternatively, touching on what darin said, try this:

或者,谈谈darin所说的,试试这个:

public ActionResult MyFirstAction()
{
    return RedirectToAction("MyNextAction",
        new { r = Request.Url.ToString() });
}

then:

然后:

public ActionResult MyNextAction()
{
    return Redirect(Request.QueryString["r"]);
}

#2


35  

If you want to redirect from a button in the View you could use:

如果要从视图中的按钮重定向,可以使用:

@Html.ActionLink("Back to previous page", null, null, null, new { href = Request.UrlReferrer})

#3


25  

If you are not concerned with unit testing then you can simply write:

如果您不关心单元测试,那么您可以简单地写:

return Redirect(ControllerContext.HttpContext.Request.UrlReferrer.ToString());

#4


8  

A suggestion for how to do this such that:

关于如何这样做的建议:

  1. the return url survives a form's POST request (and any failed validations)
  2. 返回url经受住表单的POST请求(以及任何失败的验证)
  3. the return url is determined from the initial referral url
  4. 返回url由初始的引用url决定
  5. without using TempData[] or other server-side state
  6. 不使用TempData[]或其他服务器端状态
  7. handles direct navigation to the action (by providing a default redirect)
  8. 处理指向操作的直接导航(通过提供默认重定向)

.

public ActionResult Create(string returnUrl)
{
    // If no return url supplied, use referrer url.
    // Protect against endless loop by checking for empty referrer.
    if (String.IsNullOrEmpty(returnUrl)
        && Request.UrlReferrer != null
        && Request.UrlReferrer.ToString().Length > 0)
    {
        return RedirectToAction("Create",
            new { returnUrl = Request.UrlReferrer.ToString() });
    }

    // Do stuff...
    MyEntity entity = GetNewEntity();

    return View(entity);
}

[AcceptVerbs(HttpVerbs.Post)]
public ActionResult Create(MyEntity entity, string returnUrl)
{
    try
    {
        // TODO: add create logic here

        // If redirect supplied, then do it, otherwise use a default
        if (!String.IsNullOrEmpty(returnUrl))
            return Redirect(returnUrl);
        else
            return RedirectToAction("Index");
    }
    catch
    {
        return View();  // Reshow this view, with errors
    }
}

You could use the redirect within the view like this:

您可以使用视图中的重定向如下:

<% if (!String.IsNullOrEmpty(Request.QueryString["returnUrl"])) %>
<% { %>
    <a href="<%= Request.QueryString["returnUrl"] %>">Return</a>
<% } %>

#5


6  

Pass a returnUrl parameter (url encoded) to the change and login actions and inside redirect to this given returnUrl. Your login action might look something like this:

将returnUrl参数(url编码)传递到更改和登录操作,并在内部重定向到给定的returnUrl。您的登录操作可能是这样的:

public ActionResult Login(string returnUrl) 
{
    // Do something...
    return Redirect(returnUrl);
}

#6


6  

In Mvc using plain html in View Page with java script onclick

在Mvc中,在视图页面中使用纯html和java脚本onclick

<input type="button" value="GO BACK" class="btn btn-primary" 
onclick="location.href='@Request.UrlReferrer'" />

This works great. hope helps someone.

这是伟大的。希望可以帮助别人。

@JuanPieterse has already answered using @Html.ActionLink so if possible someone can comment or answer using @Url.Action

@JuanPieterse已经使用@Html回复。ActionLink,如果可能的话,某人可以使用@Url.Action评论或回答

#7


2  

I'm using .Net Core 2 MVC , and this one worked for me, in the controller use HttpContext.Request.Headers["Referer"];

我使用。net Core 2 MVC,这个在控制器中使用httpcontext。request。header ["Referer"];

#8


1  

You could return to the previous page by using ViewBag.ReturnUrl property.

您可以使用ViewBag返回到前一页。ReturnUrl财产。

#9


1  

To dynamically construct the returnUrl in any View, try this:

要动态构建returnUrl,请尝试以下方法:

@{
    var formCollection =
        new FormCollection
            {
                new FormCollection(Request.Form),
                new FormCollection(Request.QueryString)
            };

    var parameters = new RouteValueDictionary();

    formCollection.AllKeys
        .Select(k => new KeyValuePair<string, string>(k, formCollection[k])).ToList()
        .ForEach(p => parameters.Add(p.Key, p.Value));
}

<!-- Option #1 -->
@Html.ActionLink("Option #1", "Action", "Controller", parameters, null)

<!-- Option #2 -->
<a href="/Controller/Action/@object.ID?returnUrl=@Url.Action(ViewContext.RouteData.Values["action"].ToString(), ViewContext.RouteData.Values["controller"].ToString(), parameters)">Option #2</a>

<!-- Option #3 -->
<a href="@Url.Action("Action", "Controller", new { object.ID, returnUrl = Url.Action(ViewContext.RouteData.Values["action"].ToString(), ViewContext.RouteData.Values["controller"].ToString(), parameters) }, null)">Option #3</a>

This also works in Layout Pages, Partial Views and Html Helpers

这也适用于布局页面、部分视图和Html helper

Related: MVC3 Dynamic Return URL (Same but from within any Controller/Action)

相关:MVC3动态返回URL(相同但来自任何控制器/操作)

#1


127  

try:

试一试:

public ActionResult MyNextAction()
{
    return Redirect(Request.UrlReferrer.ToString());
}

alternatively, touching on what darin said, try this:

或者,谈谈darin所说的,试试这个:

public ActionResult MyFirstAction()
{
    return RedirectToAction("MyNextAction",
        new { r = Request.Url.ToString() });
}

then:

然后:

public ActionResult MyNextAction()
{
    return Redirect(Request.QueryString["r"]);
}

#2


35  

If you want to redirect from a button in the View you could use:

如果要从视图中的按钮重定向,可以使用:

@Html.ActionLink("Back to previous page", null, null, null, new { href = Request.UrlReferrer})

#3


25  

If you are not concerned with unit testing then you can simply write:

如果您不关心单元测试,那么您可以简单地写:

return Redirect(ControllerContext.HttpContext.Request.UrlReferrer.ToString());

#4


8  

A suggestion for how to do this such that:

关于如何这样做的建议:

  1. the return url survives a form's POST request (and any failed validations)
  2. 返回url经受住表单的POST请求(以及任何失败的验证)
  3. the return url is determined from the initial referral url
  4. 返回url由初始的引用url决定
  5. without using TempData[] or other server-side state
  6. 不使用TempData[]或其他服务器端状态
  7. handles direct navigation to the action (by providing a default redirect)
  8. 处理指向操作的直接导航(通过提供默认重定向)

.

public ActionResult Create(string returnUrl)
{
    // If no return url supplied, use referrer url.
    // Protect against endless loop by checking for empty referrer.
    if (String.IsNullOrEmpty(returnUrl)
        && Request.UrlReferrer != null
        && Request.UrlReferrer.ToString().Length > 0)
    {
        return RedirectToAction("Create",
            new { returnUrl = Request.UrlReferrer.ToString() });
    }

    // Do stuff...
    MyEntity entity = GetNewEntity();

    return View(entity);
}

[AcceptVerbs(HttpVerbs.Post)]
public ActionResult Create(MyEntity entity, string returnUrl)
{
    try
    {
        // TODO: add create logic here

        // If redirect supplied, then do it, otherwise use a default
        if (!String.IsNullOrEmpty(returnUrl))
            return Redirect(returnUrl);
        else
            return RedirectToAction("Index");
    }
    catch
    {
        return View();  // Reshow this view, with errors
    }
}

You could use the redirect within the view like this:

您可以使用视图中的重定向如下:

<% if (!String.IsNullOrEmpty(Request.QueryString["returnUrl"])) %>
<% { %>
    <a href="<%= Request.QueryString["returnUrl"] %>">Return</a>
<% } %>

#5


6  

Pass a returnUrl parameter (url encoded) to the change and login actions and inside redirect to this given returnUrl. Your login action might look something like this:

将returnUrl参数(url编码)传递到更改和登录操作,并在内部重定向到给定的returnUrl。您的登录操作可能是这样的:

public ActionResult Login(string returnUrl) 
{
    // Do something...
    return Redirect(returnUrl);
}

#6


6  

In Mvc using plain html in View Page with java script onclick

在Mvc中,在视图页面中使用纯html和java脚本onclick

<input type="button" value="GO BACK" class="btn btn-primary" 
onclick="location.href='@Request.UrlReferrer'" />

This works great. hope helps someone.

这是伟大的。希望可以帮助别人。

@JuanPieterse has already answered using @Html.ActionLink so if possible someone can comment or answer using @Url.Action

@JuanPieterse已经使用@Html回复。ActionLink,如果可能的话,某人可以使用@Url.Action评论或回答

#7


2  

I'm using .Net Core 2 MVC , and this one worked for me, in the controller use HttpContext.Request.Headers["Referer"];

我使用。net Core 2 MVC,这个在控制器中使用httpcontext。request。header ["Referer"];

#8


1  

You could return to the previous page by using ViewBag.ReturnUrl property.

您可以使用ViewBag返回到前一页。ReturnUrl财产。

#9


1  

To dynamically construct the returnUrl in any View, try this:

要动态构建returnUrl,请尝试以下方法:

@{
    var formCollection =
        new FormCollection
            {
                new FormCollection(Request.Form),
                new FormCollection(Request.QueryString)
            };

    var parameters = new RouteValueDictionary();

    formCollection.AllKeys
        .Select(k => new KeyValuePair<string, string>(k, formCollection[k])).ToList()
        .ForEach(p => parameters.Add(p.Key, p.Value));
}

<!-- Option #1 -->
@Html.ActionLink("Option #1", "Action", "Controller", parameters, null)

<!-- Option #2 -->
<a href="/Controller/Action/@object.ID?returnUrl=@Url.Action(ViewContext.RouteData.Values["action"].ToString(), ViewContext.RouteData.Values["controller"].ToString(), parameters)">Option #2</a>

<!-- Option #3 -->
<a href="@Url.Action("Action", "Controller", new { object.ID, returnUrl = Url.Action(ViewContext.RouteData.Values["action"].ToString(), ViewContext.RouteData.Values["controller"].ToString(), parameters) }, null)">Option #3</a>

This also works in Layout Pages, Partial Views and Html Helpers

这也适用于布局页面、部分视图和Html helper

Related: MVC3 Dynamic Return URL (Same but from within any Controller/Action)

相关:MVC3动态返回URL(相同但来自任何控制器/操作)