HOW TO CALL URLHELPER IN ASP.NET MVC?

Ankit Singh

Total Post:341

Points:2389
Posted by  Ankit Singh
 1425  View(s)
Ratings:
Rate this:

I need to generate some URLs in a model in ASP.NET MVC. I'd like to call something like UrlHelper.Action() which uses the routes to generate the URL. I don't mind filling the usual blanks, like the hostname, scheme and so on.

Is there any method I can call for that? Is there a way to construct an UrlHelper?

  1. Tanuj Kumar

    Post:134

    Points:940
    Re: How to call UrlHelper in Asp.net MVC?

    I like Omar's answer but that's not working for me. Just for the record this is the solution I'm using now:

    var httpContext = HttpContext.Current;
    if (httpContext == null) {
      var request = new HttpRequest("/", "http://example.com", "");
      var response = new HttpResponse(new StringWriter());
      httpContext = new HttpContext(request, response);
    }
    var httpContextBase = new HttpContextWrapper(httpContext);
    var routeData = new RouteData();
    var requestContext = new RequestContext(httpContextBase, routeData);
    return new UrlHelper(requestContext);

      Modified On Apr-07-2018 12:26:16 AM

Answer

NEWSLETTER

Enter your email address here always to be updated. We promise not to spam!