views:

41

answers:

1

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
Can I generate a URL another way? I wonder why I need to know the current RequestContext just to generate a new URL.
Slack
P.S. This works. Thx.
Slack
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
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
@Tomas Lycken. OK, that makes sense. Thanks.
Slack