【问题标题】:Why can't I redirect to Index?为什么我不能重定向到索引?
【发布时间】:2021-07-01 08:11:40
【问题描述】:

设置cookie后我无法返回任何地方,cookie设置正确但设置cookie后它不会重定向到任何地方

这是我的代码:

<a onclick="changeGuestCity(@city.LocationId)">
   <span class="font-400 opacity-70">@city.LocationTitle</span>
</a>

这是 JavaScript 的函数:

<script>

        function changeGuestCity(id) {
            $.get("/Home/ChangeGuestCity/" + id);
        }

</script>

这是我的函数,但不会重定向到索引或其他任何地方:

 public IActionResult Index()
 {
     return View();
 }



 public IActionResult ChangeGuestCity(int? id)
 {

     if (id == null)
         return Redirect("/");

     CookieOptions cityCookie = new CookieOptions()
     {
         Expires = DateTime.Now.AddDays(30)
     };

     Response.Cookies.Append("city", id.ToString(), cityCookie);

     return Redirect("/");
 }

【问题讨论】:

  • 浏览器控制台有错误吗?
  • ajax 请求中的重定向仅将响应重定向到该请求。根据您似乎想要的流程,不确定您为什么在这里使用 ajax。可以用location.href = "/Home/ChangeGuestCity/" + id做你想做的事
  • @Crowcoder JS 代码工作正常,它将 LocationId 发送到我的控制器的方法 (ChangeGuestCity),并且 ChangeGuestCity 的方法也设置了 cookie。但返回不起作用!
  • 您不应该将 id 设置为查询参数,还是在 ChangeGuestCity 实现中指定 id 是 url 段?例如/Home/ChangeGuestCity/?id="+id[Route("/Home/ChangeGuestCity/{id}")]
  • 该操作将正确返回重定向,但您在 JavaScript 中的 AJAX 调用不会尊重该结果。如果您想通过 JavaScript 调用端点,则必须使用 JavaScript 手动重定向客户端。

标签: javascript c# jquery asp.net-mvc asp.net-core


【解决方案1】:

试试这个代码:


return Index();

【讨论】:

    【解决方案2】:

    你的意思是当你点击标签时你想重定向到某个地方?

    你不能从 $.get() 重定向,这里有两种方法:

    你可以在href中设置你要指向的页面:

    &lt;a href="controller/action" onclick="changeGuestCity(@city.LocationId)"&gt;

    或在您的 javascript 中重定向:

    function changeGuestCity(id) {
            $.get("/Home/ChangeGuestCity/" + id);
            window.location.href = "controller/action";
        }
    

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 2015-01-02
      • 1970-01-01
      • 2015-03-02
      • 1970-01-01
      • 2015-08-04
      • 2018-01-30
      • 2010-12-09
      相关资源
      最近更新 更多