How do I use @Html.Actionlink to create links to a multi-trace route?

Asked

Viewed 1,209 times

3

I’d like to use @Html.Actionlink to create the following link:

http://localhost:59278/video/categoria/new-movies/3

Being that my control is:

[Route("video/categoria/new-movies/{page?}")]
public async Task<ActionResult> Index(int? page)
{

}

I know how to use the @Html.ActionLink passing parameters, but in this case the page parameter is part of the route.

1 answer

2


Are you using the Attribute Routing, then remembering only that you should call the method Mapmvcattributeroutes() your RouteConfig with the following line:

routes.MapMvcAttributeRoutes();

Done this, just add the attribute into your controller, the same way you’re doing.

[Route("video/categoria/new-movies/{page?}")]
public async Task<ActionResult> Index(int? page)
{

}

Up to this part I suppose you already own, so now let’s go to yours Actionlink().

@Html.ActionLink("TEXTO","Index","CONTROLLER",  new { page = 3 }, null)

Remembering that his actionLink "works" as follows:

MvcHtmlString HtmlHelper.ActionLink(
    string linkText, 
    string actionName, 
    string controllerName, 
    object routeValues, 
    object htmlAttributes
)

The "roughly", first you pass the text, then the Action, the Controller, path values and html attributes.

As you can see, in the ActionLink "you don’t care" about the routes, just call the Action and the Controller, remembering to pass the necessary parameters.

  • It worked now when I put an extra variable in the control , string sort and one more in HTML.Actionlink new { page = 3, sort = "newest" } it generates the url like this: http://localhost:59278/video/categoria/new-movies/3?sort=newest.. It shouldn’t generate like this: http://localhost:59278/video/categoria/new-movies/3/newest? What I did wrong?

  • If you change only on ActionLink it will add as queryString. To avoid this, you must change your route, more or even like this: [Route("video/categoria/new-movies/{page?}/{sort}")]

  • Yeah, I did it too... I forgot to put [Route("video/categoria/{categoria}/{page?}/{sort?}")] but it didn’t work no... Strange

  • Note that you are passing the category as parameter {categoria}, and not as a fixed value /categoria/.

  • Putz, I’m changing the wrong way, it worked, thank you!

Browser other questions tagged

You are not signed in. Login or sign up in order to post.