5
public class HomeController : Controller
{
    [Route("Users/about")]
    [Route("Users/WhoareWe")]
    [Route("Users/OurTeam")]
    [Route("Users/aboutCompany")]
    public ActionResult GotoAbout()
    {
        return View();
    }
}

I have many routes defined for action GotoAbout().

How to create route URL in razor page programmatically when generate URL for action like home/users/about ?

2
  • Give the route a name and reference route directly by name. Commented Jun 18, 2017 at 21:58
  • how to do it....can you give me a small example code if possible. Commented Jun 18, 2017 at 22:15

1 Answer 1

7

Reference Attribute Routing in ASP.NET MVC 5 - Route Names

You can specify a name for a route, in order to easily allow URI generation for it.

For example, for the following route:

[RoutePrefix("Home")]
public class HomeController : Controller {
    [Route("Users/about", Name = "Users_About")]
    [Route("Users/WhoareWe")]
    [Route("Users/OurTeam")]
    [Route("Users/aboutCompany")]
    public ActionResult GotoAbout() {
        return View();
    }
}

you could generate a link using Url.RouteUrl:

<a href="@Url.RouteUrl("Users_About")">About</a>

which would resolve to

<a href="home/users/about">About</a>
Sign up to request clarification or add additional context in comments.

4 Comments

can i generate route url like this way @Html.RouteLink(Model.PostTitle, " ArticlesPost ", new { category = Model.postCategory.Category, url = Model.PostUrl }, new { @class = "title" }) code taken from dotnet-tutorial.com/articles/mvc/…
What would be the alternative for ASP.NET 6.0 where RoutePrefix doesn't exist?
@MendiSterenfeld it has been replaced with just Route attribute. Reference: Routing to controller actions in ASP.NET Core
@Nkosi took me a few hours to figure it out, still having problems with combining the Prefix with the Method in the cshtml. Check out my last question. thank you

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.