David Neale
David Neale

Reputation: 17028

Accessing System.Web.Routing.RequestContext from static context in MVC 2.0

I need to use System.Web.Routing.RequestContext in a view model in order to call HtmlHelper.GenerateLink().

In MVC 1.0 it was possible to get the context statically by casting the current IHttpHandler:

 var context = ((MvcHandler) HttpContext.Current.CurrentHandler).RequestContext;

Now the project has been upgraded to MVC 2.0 and this exception is thrown on the cast:

Unable to cast object of type 'ServerExecuteHttpHandlerWrapper' to type 'System.Web.Mvc.MvcHandler'.

I'm not sure if it's relevant but this is being run in .NET 4.0 on IIS6.

Upvotes: 7

Views: 19079

Answers (2)

benwasd
benwasd

Reputation: 1352

I don't know what you wanna do with the System.Web.Routing.RequestContext? check out:

var context = new HttpContextWrapper(System.Web.HttpContext.Current);
var routeData = RouteTable.Routes.GetRouteData(context);

// Use RouteData directly:
var controller = routeData.Values["controller"];

// Or with via your RequestContext:
var requestContext = new RequestContext(context, routeData);
controller = requestContext.RouteData.Values["controller"]

Upvotes: 11

Darin Dimitrov
Darin Dimitrov

Reputation: 1038930

I need to use System.Web.Routing.RequestContext in a view model in order to call HtmlHelper.GenerateLink().

While in theory you could write:

var rc = HttpContext.Current.Request.RequestContext;

in practice you should absolutely never be doing something like this in a view model. That's what HTML helpers are supposed to do:

public static MvcHtmlString GenerateMyLink<MyViewModel>(this HtmlHelper<MyViewModel> html)
{
    MyViewModel model = html.ViewData.Model;
    RequestContext rc = html.ViewContext.RequestContext;
    //TODO: use your view model and the HttpContext to generate whatever link is needed
    ...
}

and in your strongly typed to MyViewModel view simply:

<%= Html.GenerateMyLink() %>

Upvotes: 17

Related Questions