代码之家  ›  专栏  ›  技术社区  ›  Roy Tinker

ASP.NET MVC-获取不包含传递的ID的当前操作的URL

  •  2
  • Roy Tinker  · 技术社区  · 15 年前

    以下是我的行动:

    public ActionResult Edit(int? id)
    {
        if (id != null) return Redirect(Url.Action("Edit") + "/#" + id);
    
        return View();
    }
    

    问题是Url.Action方法保留传递的id。Url.Action(“编辑”)返回“{controller}/Edit/{id}”。我希望它只返回“{controller}/Edit”(我的代码附加了一个“/#{id}”)。

    http://localhost:2471/Events/Edit/22
    

    http://localhost:2471/Events/Edit/22/#22
    

    当我希望它重定向到此URL时:

    http://localhost:2471/Events/Edit/#22
    

    我很沮丧。有人知道如何获取不包含传递id的当前操作的URL吗?

    3 回复  |  直到 15 年前
        1
  •  1
  •   Chris Shaffer    15 年前

    一种方法是为控制器操作定义一个路由,例如将路由定义为“{controller}/{action}/”。然后使用类似于以下内容的内容来构建您的实际URL:

    Url.RouteUrl("MyRoute") + "#" + id
    

    这不是最好的方法,但很有效。也许有一天微软会在路由中添加碎片支持。

        3
  •  0
  •   Chris Shaffer    15 年前

    Url.Action("Edit", "Events", new { id = "#" + id });
    

    或者也可以用同样的方法使用RedirectToAction()。

    另一种方法是定义路由{controller}/{Action}/#{id},然后使用Url.Route()代替。