Shawn Mclean
Shawn Mclean

Reputation: 57469

How do I generate a URL outside of a controller in ASP.NET MVC?

How do I generate a URL pointing to a controller action from a helper method outside of the controller?

Upvotes: 40

Views: 32072

Answers (5)

mohammadmahdi Talachi
mohammadmahdi Talachi

Reputation: 601

You can use LinkGenerator . It's new feature in Microsoft.AspNetCore.Routing namespace and has been added in Aug 2020 .

At first you have to inject that in your class :

public class Sampleervice 
{
        private readonly LinkGenerator _linkGenerator;

        public Sampleervice (LinkGenerator linkGenerator)
       {
            _linkGenerator = linkGenerator;
       }

       public string GenerateLink()
       { 
             return _linkGenerator.GetPathByAction("Privacy", "Home");
       }
}

For more information check this

Upvotes: 6

Alexei - check Codidact
Alexei - check Codidact

Reputation: 23078

Using L01NL's answer, it might be important to note that Action method will also get current parameter if one is provided. E.g:

editing project with id = 100 Url is http://hostname/Project/Edit/100

urlHelper.Action("Edit", "Project") returns http://hostname/Project/Edit/100

while urlHelper.Action("Edit", "Project", new { id = (int?) null }); returns http://hostname/Project/Edit

Upvotes: 2

L01NL
L01NL

Reputation: 1813

You could use the following if you have access to the HttpContext:

var urlHelper = new UrlHelper(HttpContext.Current.Request.RequestContext);

Upvotes: 101

Mahesh Velaga
Mahesh Velaga

Reputation: 21991

Pass UrlHelper to your helper function and then you could do the following:

public SomeReturnType MyHelper(UrlHelper url, // your other parameters)
{
   // Your other code

   var myUrl =  url.Action("action", "controller");

  // code that consumes your url
}

Upvotes: -5

Tomas Aschan
Tomas Aschan

Reputation: 60564

Since you probably want to use the method in a View, you should use the Url property of the view. It is of type UrlHelper, which allows you to do

<%: Url.Action("TheAction", "TheController") %>

If you want to avoid that kind of string references in your views, you could write extension methods on UrlHelper that creates it for you:

public static class UrlHelperExtensions
{
    public static string UrlToTheControllerAction(this UrlHelper helper)
    {
        return helper.Action("TheAction", "TheController");
    }
}

which would be used like so:

<%: Url.UrlToTheControllerTheAction() %>

Upvotes: 1

Related Questions