c# - ASP.NET MVC 路由将用户从局部 View 返回到原点

标签 c# asp.net asp.net-mvc asp.net-mvc-4

我在 Visual Studio 2015 中使用 ASP.NET MVC。该应用具有以下结构:

  • 我的应用

    • Controller

      • Controller 1
        • 行动
          • 创建
          • 删除
          • 详细信息
          • 编辑
          • 部分索引
      • Controller 2
        • 行动
          • 编辑
      • Controller 3
        • 行动
          • 编辑
    • 观看次数

      • Controller 1
        • 创建
        • 删除
        • 详细信息
        • 编辑
        • 部分索引
      • Controller 2
        • 编辑
      • Controller 3
        • 编辑

应用程序在 Controller2/Edit View 和 Controller3/Edit 上显示 Controller1/IndexPartial View 。此部分 View 显示数据行,每行数据都带有 EditDetailsDelete 按钮,这些按钮将用户带到 Controller1 对这些操作的看法。

当用户完成 Controller1 操作后,他们需要通过 Back to List 返回到 Controller2/EditController3/Edit > 按钮或单击保存/删除按钮时。但是我们如何确定用户来自哪里?用户是否来自 Controller2Controller3Edit

我们考虑过使用 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/

相关文章:

javascript - 如何向 asp c# webMethod 发送参数?使用 Ajax Jquery

c# - 是否可以使用数据注释来验证传递给 Controller ​​的 Action 方法的参数?

c# - 在asp.net mvc中,如何添加验证

c# - 为什么 System.Type.GetHashCode 会为所有实例和类型返回相同的值?

c# - 如何检查是否已超过 30 天?

c# - 在 Ninject 中查找抽象类绑定(bind)到哪个类

c# - Infragistics Ultragrid - 选择最右边的列时不要移动到行下方

asp.net - 已将 'multipart/form-data' 上传到 ASP.NET Web API 操作,在无缓冲模式下不可读

c# - 不需要地显示 jgrowl 消息

asp.net-mvc - 如何为 jqGrid 启用 excel 导出按钮