Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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.

like image 259
David Neale Avatar asked May 26 '11 09:05

David Neale


2 Answers

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() %>
like image 105
Darin Dimitrov Avatar answered Nov 16 '22 10:11

Darin Dimitrov


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"]
like image 11
benwasd Avatar answered Nov 16 '22 12:11

benwasd