我在 Visual Studio 2015 中使用 ASP.NET MVC。该应用具有以下结构:
我的应用
Controller
- Controller 1
- 行动
- 创建
- 删除
- 详细信息
- 编辑
- 部分索引
- 行动
- Controller 2
- 行动
- 编辑
- 行动
- Controller 3
- 行动
- 编辑
- 行动
- Controller 1
观看次数
- Controller 1
- 创建
- 删除
- 详细信息
- 编辑
- 部分索引
- Controller 2
- 编辑
- Controller 3
- 编辑
- Controller 1
应用程序在 Controller2/Edit
View 和 Controller3/Edit
上显示 Controller1/IndexPartial
View 。此部分 View 显示数据行,每行数据都带有 Edit
、Details
、Delete
按钮,这些按钮将用户带到 Controller1
对这些操作的看法。
当用户完成 Controller1 操作后,他们需要通过 Back to List
返回到 Controller2/Edit
或 Controller3/Edit
> 按钮或单击保存/删除按钮时。但是我们如何确定用户来自哪里?用户是否来自 Controller2
或 Controller3
的 Edit
?
我们考虑过使用 session 变量。 RouteConfig.cs
能否用于跟踪用户的路径并帮助确定他/她应该返回的位置?我们如何通过 MVC 中的路由来做到这一点?
感谢您的帮助。
更新:这一切都是通过服务器完成的;没有 JavaScript(Angular 等)。
最佳答案
路由引擎与您的需求无关。您需要跟踪用户导航,执行此操作的一个好方法是使用 ActionFilters。
您可以创建自定义 ActionFilter,检查 UrlReferrer 的 OnActionExecuted 并决定如何将请求重定向到适当的 Controller/Action。
[例子]
Action 过滤器
public class RedirectAfterActionFilter : ActionFilterAttribute, IActionFilter
{
public override void OnActionExecuted(ActionExecutedContext filterContext)
{
// Your decision logic
if (filterContext.HttpContext.Request.UrlReferrer.AbsolutePath == "something usefull")
{
filterContext.Result = new RedirectToRouteResult("Your Route Name", routeValues: null); // redirect to Home
}
base.OnActionExecuted(filterContext);
}
}
ActionFilter 的使用
[RedirectAfterActionFilter]
public ActionResult DoSomethingAndGetRedirected()
{
// Save, Edit or Whatever
//...
return new EmptyResult(); // no need to return since the user will be redirected by the filter
}
额外:阅读How to redirect from a action filter如果您不喜欢使用路由名称进行重定向。
关于c# - ASP.NET MVC 路由将用户从局部 View 返回到原点,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/41145816/