ASP.NET MVC - 获取当前操作的 URL(不包含传递的 ID)
我有一个操作,我想拦截任何可能出现的整数 id 并将其放置在哈希后面。 (我有一些正在处理 id 的 Javascript)。我这样做只是为了像我这样的 URL 黑客,他们可能会忘记我在 id 之前添加哈希值的惯例。
这是我的操作:
public ActionResult Edit(int? id)
{
if (id != null) return Redirect(Url.Action("Edit") + "/#" + id);
return View();
}
问题是 Url.Action 方法保留了传递的 id。 Url.Action("Edit") 返回“{controller}/Edit/{id}”。我希望它只返回“{controller}/Edit”! (我的代码附加了一个额外的“/#{id}”)。
例如,对此 URL: 的请求
http://localhost:2471/Events/Edit/22
正在重定向到此 URL:
http://localhost:2471/Events/Edit/22/#22
当我希望它重定向到此 URL: 时,
http://localhost:2471/Events/Edit/#22
我感到沮丧。有谁知道如何获取当前操作的 URL(不包含传递的 id)?
I have an action in which I want to intercept any possible integer id that comes and place it behind a hash. (I have some Javascript that is handling the id). I am only doing this extra step for the sake of URL-hackers like me who might forget my convention of putting a hash before the id.
Here is my action:
public ActionResult Edit(int? id)
{
if (id != null) return Redirect(Url.Action("Edit") + "/#" + id);
return View();
}
The problem is that the Url.Action method is preserving the passed id. Url.Action("Edit") is returning "{controller}/Edit/{id}". I want it to just return "{controller}/Edit"! (And my code is tacking on an additional "/#{id}").
For example, a request to this URL:
http://localhost:2471/Events/Edit/22
is redirecting to this URL:
http://localhost:2471/Events/Edit/22/#22
when I want it to redirect to this URL:
http://localhost:2471/Events/Edit/#22
I'm frustrated. Does anyone know how to get a URL to the current action that doesn't include the passed id?
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(3)
实现此目的的一种方法是为控制器操作定义路由,例如,路由将定义为“{controller}/{action}/”。然后使用类似于以下内容的方法来构建您的实际 URL:
不是最好的方法,但它有效。也许有一天微软会为路由添加片段支持。
One way to do this would be to define a route for the controller action, eg the Route would be defined as "{controller}/{action}/". Then use something similar to the following to build your actual URL:
Not the best method, but it works. Maybe someday Microsoft will add fragment support to routing.
我不完全确定,但您可以使用 RedirectToAction 方法吗?
http://msdn.microsoft.com/ en-us/library/system.web.mvc.controller.redirecttoaction.aspx
I'm not completely sure but could you use the RedirectToAction method ?
http://msdn.microsoft.com/en-us/library/system.web.mvc.controller.redirecttoaction.aspx
我不是 100% 确定(并且没有我的开发机器来测试),但我认为你可以在 id 参数中传递哈希,它会起作用...例如:
或者你可以使用 RedirectToAction() 相同方式。
另一种方法是定义一个 Route {controller}/{Action}/#{id},然后使用 Url.Route() 代替。
I'm not 100% sure (and don't have my dev machine to test), but I think you could pass the hash within the id parameter and it would work...eg:
or you could use RedirectToAction() the same way.
An alternative would be to define a Route {controller}/{Action}/#{id} and then use Url.Route() instead.