【问题标题】:MVC Core - Return to previous pageMVC 核心 - 返回上一页
【发布时间】:2018-08-14 14:20:53
【问题描述】:

是否可以在 ASP.Net Core 中的 controller 操作上返回上一页?

示例:

假设我们有以下controllers

  • HomeController 有动作Index() 返回View()
  • BlogPostController 有动作BlogPosts() 返回View(model)
  • PostController(相同)与动作BlogPost(int postId) 返回View(model)

_Layout 上还有一个按钮(因此它在所有其他Views 中都可用),单击该按钮即可在GlobalController 中执行DoSomething()。由于我的应用程序中的所有Views 都可以调用DoSomething(),因此我希望它只创建一个cookie 并重新加载上一页,而不必重定向到确切的操作。

更具体地说:如果我在http://mysite/index 上调用DoSomething(),我希望它创建一个cookie 并返回http://mysite/index 并重新加载它。我在http://mysite/BlogPost?postId=13 时的情况也是如此。

这在 ASP.Net Core 2.0 中可行吗?如果是,如何实现?

【问题讨论】:

  • 不确定是否使用 cookie/控制器操作,但我发现可以使用 JS - 返回
  • 也看到了,但我认为它会在点击时返回,而不是从控制器的DoSomething() 方法中执行操作,我需要先完成它们。

标签: asp.net asp.net-mvc asp.net-core .net-core


【解决方案1】:

history.go(-1) 的问题是,如果你刚刚提交了一个表单,它会尝试再次提交表单......

也许您可以添加一个全局操作过滤器,使用以下方式检查引荐来源:

Request.Headers["Referer"]

然后按照您的建议将引用 url 存储在 cookie 中,但仅在检查它是 GET 而不是帖子之后?

【讨论】:

    【解决方案2】:

    如果您使用的是 .Net Core 3.1,您的控制器方法中的这一行将重定向到上一页 return Redirect(HttpContext.Request.Headers["Referer"]);

    这就是你所需要的......

    【讨论】:

      【解决方案3】:

      不确定这是否是正确的方法,但我已经通过以下方式“破解”了它:

      1. 将我的控制器操作返回类型更改为void
      2. 在我的控制器操作中设置Response.StatusCode = 204(204 是成功的代码,无需额外内容)
      3. 通过 ajax 从视图调用我的操作,成功时使用 location.reload()

      如果您有任何关于该解决方案的 cmets,请告诉我。我不确定这是否是要遵循的方法,所以我很高兴听到更有经验的网络开发人员的意见。

      【讨论】:

        【解决方案4】:
        [HttpGet] // This isn't required
        public ActionResult Edit(int id)
        {
            // load object and return in view
            ViewModel viewModel = Load(id);
        
            // get the previous url and store it with view model
            viewModel.PreviousUrl = System.Web.HttpContext.Current.Request.UrlReferrer;
        
            return View(viewModel);
        }
        
        [HttpPost]
        public ActionResult Edit(ViewModel viewModel)
        {
            // Attempt to save the posted object if it works, return index if not return the Edit view again
        
            bool success = Save(viewModel);
            if (success)
            {
                return Redirect(viewModel.PreviousUrl);
            }
            else
            {
                ModelState.AddModelError("There was an error");
                return View(viewModel);
            }
        }
        

        您的视图的BeginForm 方法也不需要使用此返回URL,您应该能够逃脱:

        @model ViewModel
        
        @using (Html.BeginForm())
        {
            ...
            <input type="hidden" name="PreviousUrl" value="@Model.PreviousUrl" />
        }
        

        【讨论】:

          猜你喜欢
          • 1970-01-01
          • 2012-04-04
          • 1970-01-01
          • 1970-01-01
          • 2020-12-09
          • 2017-07-02
          • 2023-03-27
          • 1970-01-01
          • 1970-01-01
          相关资源
          最近更新 更多