在 ASP.NET MVC 的模型中调用 UrlHelper
我需要在 ASP.NET MVC 的模型中生成一些 URL。我想调用类似 UrlHelper.Action() 的方法,它使用路由来生成 URL。我不介意填写常见的空白,例如主机名、方案等。
我可以调用任何方法吗?有没有办法构造一个UrlHelper?
I need to generate some URLs in a model in ASP.NET MVC. I'd like to call something like UrlHelper.Action() which uses the routes to generate the URL. I don't mind filling the usual blanks, like the hostname, scheme and so on.
Is there any method I can call for that? Is there a way to construct an UrlHelper?
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(8)
当前 HttpContext 的引用
有用的提示,在任何 ASP.NET 应用程序中,您都可以获取派生自 System.Web 的 。因此,以下内容将在 ASP.NET MVC 应用程序中的任何位置工作:
示例:
在创建的 MyModel 对象上调用
Link
属性将返回有效的 Url,以根据 Global.asax 中的路由查看模型Helpful tip, in any ASP.NET application, you can get a reference of the current HttpContext
which is derived from System.Web. Therefore, the following will work anywhere in an ASP.NET MVC application:
Example:
Calling the
Link
property on a created MyModel object will return the valid Url to view the Model based on the routing in Global.asax我喜欢奥马尔的回答,但这对我不起作用。仅供记录,这是我现在使用的解决方案:
I like Omar's answer but that's not working for me. Just for the record this is the solution I'm using now:
可以通过以下方式从 Controller 操作内部构造 UrlHelper:
在控制器外部,可以通过从 RouteTable.Routes RouteData 创建 RequestContext 来构造 UrlHelper。
(基于 Brian 的回答,添加了少量代码更正。)
A UrlHelper can be constructed from within a Controller action with the following:
Outside of a controller, a UrlHelper can be constructed by creating a RequestContext from the RouteTable.Routes RouteData.
(Based on Brian's answer, with a minor code correction added.)
是的,您可以实例化它。你可以这样做:
RouteTable.Routes
是一个静态属性,所以你应该没问题;为了获取HttpContextBase
引用,HttpContextWrapper
获取对HttpContext
的引用,然后HttpContext
传递该引用。Yes, you can instantiate it. You can do something like:
RouteTable.Routes
is a static property, so you should be OK there; to get aHttpContextBase
reference,HttpContextWrapper
takes a reference toHttpContext
, andHttpContext
delivers that.在尝试了所有其他答案之后,我最终得到了
仇恨者会讨厌 ́\_(ツ)_/́
After trying all the other answers, I ended up with
Haters gonna hate ¯\_(ツ)_/¯
我试图在页面内(控制器外部)执行类似的操作。
UrlHelper 不允许我像 Pablos 的回答一样轻松地构建它,但后来我想起了一个有效做同样事情的老技巧:
I was trying to do something similar from within a page (outside of a controller).
UrlHelper did not allow me to construct it as easily as Pablos answer, but then I remembered a old trick to effective do the same thing:
之前的回复对我没有帮助。我的方法是在我的 Home 控制器中创建一个与 UrlHelper 具有相同功能的操作。
作为一个操作,您可以从任何地方请求它,甚至在 Hub 内部:
您可以获取 AnonymousType 的源代码 此处。
Previous responses didn't help me. My approach has been create an action in my Home controller with the same functionality that UrlHelper.
Been an action, you can request it from anywhere, even inside the Hub:
You can get source code of AnonymousType here.
我想你正在寻找的是这样的:
I think what you're looking for is this: