asp.net-mvc 如何重定向到 ASP.NET MVC 中的上一个操作?
声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow
原文地址: http://stackoverflow.com/questions/815229/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me):
StackOverFlow
How do I redirect to the previous action in ASP.NET MVC?
提问by adolfojp
Lets suppose that I have some pages
假设我有一些页面
some.web/articles/details/5some.web/users/info/bobsome.web/foo/bar/7
some.web/articles/details/5some.web/users/info/bobsome.web/foo/bar/7
that can call a common utility controller like
可以调用一个通用的实用程序控制器,如
locale/change/esor authorization/login
locale/change/es或者 authorization/login
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)?
如何让这些方法 ( change, login) 重定向到先前的操作 ( details, info, bar),同时将先前的参数传递给它们 ( 5, bob, 7)?
In short: How do I redirect to the page that I just visited after performing an action in another controller?
简而言之:如何在另一个控制器中执行操作后重定向到我刚刚访问的页面?
回答by Nathan Ridley
try:
尝试:
public ActionResult MyNextAction()
{
return Redirect(Request.UrlReferrer.ToString());
}
alternatively, touching on what darin said, try this:
或者,触及达林所说的,试试这个:
public ActionResult MyFirstAction()
{
return RedirectToAction("MyNextAction",
new { r = Request.Url.ToString() });
}
then:
然后:
public ActionResult MyNextAction()
{
return Redirect(Request.QueryString["r"]);
}
回答by IUnknown
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})
回答by Rahatur
If you are not concerned with unit testing then you can simply write:
如果您不关心单元测试,那么您可以简单地编写:
return Redirect(ControllerContext.HttpContext.Request.UrlReferrer.ToString());
回答by shaijut
In Mvc using plain html in View Pagewith 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.ActionLinkso if possible someone can comment or answer using @Url.Action
@JuanPieterse 已经回答了 using@Html.ActionLink所以如果可能的话有人可以评论或回答使用@Url.Action
回答by shaijut
A suggestion for how to do this such that:
关于如何做到这一点的建议:
- the return url survives a form's POST request (and any failed validations)
- the return url is determined from the initial referral url
- without using TempData[] or other server-side state
- handles direct navigation to the action (by providing a default redirect)
- 返回 url 在表单的 POST 请求(以及任何失败的验证)中幸存下来
- 返回 url 由初始推荐 url 确定
- 不使用 TempData[] 或其他服务器端状态
- 处理直接导航到操作(通过提供默认重定向)
.
.
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>
<% } %>
回答by Darin Dimitrov
Pass a returnUrl parameter (url encoded) to the changeand loginactions 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);
}
回答by Saad Hasan
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.Headers["Referer"];
回答by almaceleste
You could return to the previous page by using ViewBag.ReturnUrlproperty.
您可以使用ViewBag.ReturnUrl属性返回上一页。
回答by Matthew Hudson
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/@[email protected](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 助手
Related: MVC3 Dynamic Return URL(Same but from within any Controller/Action)
相关:MVC3 动态返回 URL(相同但来自任何控制器/操作)
回答by Mohamed Elamin
For ASP.NET CoreYou can use asp-route-* attribute:
对于ASP.NET Core,您可以使用 asp-route-* 属性:
<form asp-action="Login" asp-route-previous="@Model.ReturnUrl">
Other in details example:Imagine that you have a Vehicle Controller with actions
其他细节示例:假设您有一个带有动作的 Vehicle Controller
Index
指数
Details
细节
Edit
编辑
and you can edit any vehicle from Index or from Details, so if you clicked edit from index you must return to index after edit and if you clicked edit from details you must return to details after edit.
并且您可以从索引或详细信息编辑任何车辆,因此如果您单击从索引编辑,则必须在编辑后返回索引,如果单击从详细信息编辑,则必须在编辑后返回详细信息。
//In your viewmodel add the ReturnUrl Property
public class VehicleViewModel
{
..............
..............
public string ReturnUrl {get;set;}
}
Details.cshtml
<a asp-action="Edit" asp-route-previous="Details" asp-route-id="@Model.CarId">Edit</a>
Index.cshtml
<a asp-action="Edit" asp-route-previous="Index" asp-route-id="@item.CarId">Edit</a>
Edit.cshtml
<form asp-action="Edit" asp-route-previous="@Model.ReturnUrl" class="form-horizontal">
<div class="box-footer">
<a asp-action="@Model.ReturnUrl" class="btn btn-default">Back to List</a>
<button type="submit" value="Save" class="btn btn-warning pull-right">Save</button>
</div>
</form>
In your controller:
在您的控制器中:
// GET: Vehicle/Edit/5
public ActionResult Edit(int id,string previous)
{
var model = this.UnitOfWork.CarsRepository.GetAllByCarId(id).FirstOrDefault();
var viewModel = this.Mapper.Map<VehicleViewModel>(model);//if you using automapper
//or by this code if you are not use automapper
var viewModel = new VehicleViewModel();
if (!string.IsNullOrWhiteSpace(previous)
viewModel.ReturnUrl = previous;
else
viewModel.ReturnUrl = "Index";
return View(viewModel);
}
[HttpPost]
public IActionResult Edit(VehicleViewModel model, string previous)
{
if (!string.IsNullOrWhiteSpace(previous))
model.ReturnUrl = previous;
else
model.ReturnUrl = "Index";
.............
.............
return RedirectToAction(model.ReturnUrl);
}

