Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Getting URL to action in static method in ASP.NET MVC

My ASP.NET MVC application adds a route named "Asset" to the RouteTable, and I have a static method.

This static method needs to be able to generate the URL to the "Asset" route of the application.

How can I do this?

like image 240
MvcNewb2012 Avatar asked Aug 16 '11 17:08

MvcNewb2012


People also ask

Can action method be static in MVC?

The one restriction on action method is that they have to be instance method, so they cannot be static methods. Also there is no return value restrictions. So you can return the string, integer, etc.

What is action method in URL?

Action(String, String, Object, String) Generates a fully qualified URL to an action method by using the specified action name, controller name, route values, and protocol to use.


2 Answers

The helper class:

  public static class UrlHelper
  {
    private static System.Web.Mvc.UrlHelper _urlHelper;

    public static System.Web.Mvc.UrlHelper GetFromContext()
    {
      if (_urlHelper == null)
      {
        if (HttpContext.Current == null)
        {
         throw new HttpException("Current httpcontext is null!"); 
        }

        if (!(HttpContext.Current.CurrentHandler is System.Web.Mvc.MvcHandler))
        {
          throw new HttpException("Type casting is failed!"); 
        }

        _urlHelper = new System.Web.Mvc.UrlHelper(((System.Web.Mvc.MvcHandler)HttpContext.Current.CurrentHandler).RequestContext);
      }

      return _urlHelper;
    }
  }

The calling:

UrlHelper.GetFromContext().Action("action", "controller");
like image 115
vladimir Avatar answered Sep 21 '22 19:09

vladimir


assuming your code is running in the context of a http request, you can do the following from a static method:

new UrlHelper(HttpContext.Current.Request.RequestContext);
like image 41
Paul Avatar answered Sep 19 '22 19:09

Paul