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.
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() %>
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"]
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With