Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How do i construct a route without ViewContext in ASP.NET MVC?

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

like image 259
Simon_Weaver Avatar asked Apr 07 '09 04:04

Simon_Weaver


1 Answers

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)

like image 79
eu-ge-ne Avatar answered Oct 06 '22 01:10

eu-ge-ne