views:

705

answers:

1

I want to create a route from a utility class that doesn't have access to a ViewContext.

Is this possible? There doesnt seem to be any equivalent of ViewContext.Current

I've tried fishing around in all the constructors for Routing and HttpContext but can't quite get to what I want.

This is what I'm looking for - although this doesn't work because RouteTable.Routes is of type RouteCollection and not RouteData. So close - yet so far :-)

        RequestContext requestContext = new RequestContext(HttpContext.Current, RouteTable.Routes);
        UrlHelper url = new UrlHelper(requestContext);
        var urlString = url.RouteUrl(new {controller="DynamicImage", action="Button", text="Hello World"});

Note: RequestContest is of type System.Web.Routing.RequestContext and not HttpContext

+4  A: 

Try this:

var httpContext = new HttpContextWrapper(HttpContext.Current);
var requestContext = new RequestContext(httpContext);
var urlHelper = new UrlHelper(requestContext, new RouteData()));

Hope this helps

UPDATED:

The previous is not correct (I've posted it from my memory). Try this instead (it works in one of my projects):

var httpContext = new HttpContextWrapper(HttpContext.Current)
var requestContext = new RequestContext(httpContext, new RouteData());
var urlHelper = new UrlHelper(requestContext);

new RouteData() is using just only for RequestContext initialization and new UrlHelper(requestContext) actually calls new UrlHelper(requestContext, RouteTable.Routes)

eu-ge-ne
i was surprised that that actually works. i'm just not yet sure what the implications of having an empty RouteData() object is. perhaps it uses the current route as a 'base' for the new route? anyone know?
Simon_Weaver
I've updated my answer
eu-ge-ne