将参数传递给控制器..但不在 URL 上
有没有办法将参数传递给控制器而不将其放在 URL 上?
例如, http://www.winepassionate.com/p/19/wine-chianti-docg-la-moto 的
URL 值为 19。如果您实际上将该值更改为另一个值,即使页面名称保持不变,页面也会显示不同的记录。
所以我不想在 URL 上传递 ID,但仍然能够将其传递给控制器。 推荐的方法是什么?
Is there a way to pass a parameter to a controller without putting it on the URL?
For example,
http://www.winepassionate.com/p/19/wine-chianti-docg-la-moto
has the value 19 on the URL. If you actually change that value to another, the page displays a different record even it the page name remains the same.
So I would like to NOT pass the ID on the URL but still be able to pass that to the Controller.
What's the recommended way to do so?
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。

绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(4)
您可以发布帖子并将其作为表单参数发送。我不推荐这个。帖子应该针对修改数据的请求。在这种情况下,您很可能只是为了获取该数据。 id 位于 URL 中这一事实是一件好事(请参阅 Stack Overflow URLs 以供参考)。如果您确实不希望用户能够修改它(我希望这不是因为您认为这会使它更安全,因为事实并非如此),您可以对其进行一些简单的加密以使其更难以修改猜测/产生有效的 ID。
正如其他一些人所建议的那样,使用 TempData 并不是一个可靠的解决方案。它不适用于页面上的链接,仅适用于 POST 后的 GET,并且仅适用于一次,因为 TempData 在下一个请求后被删除。
You can do a post and send it as a form parameter. I do not recommend this. Posts should be for requests that modify data. In this case you're most likely looking just to get that data. The fact that the id is in the URL is a good thing (see the Stack Overflow URLs for reference). If you really don't want the user to be able to modify it (I hope it's not because you think this makes it more secure, because it doesn't), you could do some simple encryption on it to make it more difficult to guess/produce a valid ID.
Using TempData, as some other suggest, is not a robust solution. It won't work for links on a page, just a GET after POST, and then only once since TempData is deleted after the next request.
好吧,你有几个选择:
Well, you have a couple of options:
TempData
to store this temporary value. However, I would recommend against this approach, as it is very transient and not good practice imo.如果页面是 GET,并且您按照应有的方式遵循 PRG (Post-Redirect-Get),那么您可以使用 TempData["dataName"] = value;在你的 [HttpPost] 控制器中,然后在你的 [HttpGet] 方法中使用它。这实际上取决于页面的调用方式。
但是,如果与安全无关,让用户更改该数字并没有什么问题,并且在 url 中显示非重要信息是常见的做法。
If the page is a GET, and you are following the PRG like you should be (Post-Redirect-Get) then you can use TempData["dataName"] = value; in your [HttpPost] controller and then consume it in your [HttpGet] method. It really depends on how the page is being called.
However, there is nothing wrong in letting the user change that number if it is not security related, and is common practice to show non-vital information in the url like that.
在这种情况下您应该使用 TempData。可以找到对此的详细阅读 在此博客上。
TempData 允许您在请求之间临时存储一个值,并且默认情况下在访问后会被删除。
You should use TempData in this case. A good read on this can be found on this blog.
TempData allows you to store a value temporarily between requests and is, by default, erased after being accessed.