I'm creating a Shared (static) method in ASP.NET MVC so it can be used by any controller in my project. This static method needs to generate a URL. I think I need to use System.Web.Mvc.UrlHelper, but I can't figure out how to call it from within a static method. The constructor seems to want a RequestContext. Any ideas?
+1
A:
AFAIK, there is no way to get the "current" RequestContext statically. You'll need to pass in the RequestContext from the controller that's calling it. Any controller can do that by just using this code:
this.ControllerContext.RequestContext
womp
2009-09-27 22:03:23
Can I generate a URL another way? I wonder why I need to know the current RequestContext just to generate a new URL.
Slack
2009-09-27 22:06:33
P.S. This works. Thx.
Slack
2009-09-27 22:11:37
UrlHelper is a pretty good way of doing it. You can also generate relative URLs using the routing mechanisms directly, but you'd need to pass in routing information instead.
womp
2009-09-27 22:13:20
Bob: The `RequestContext` is necessary because the generated URL will be *relative* to whatever URL the browser requested. (As you use routing, the browser has no idea that the file served isn't actually where it is "pretended" to be...) Without the `RequestContext` there's no way for the `UrlHelper` to know what the current URL is, and thus no way to generate a relative URL.
Tomas Lycken
2009-09-27 22:49:47
@Tomas Lycken. OK, that makes sense. Thanks.
Slack
2009-09-28 00:27:45