@ Html.ActionLink and Url.Action are not taking the route of the controller annotation

1

I have the following method in the control:

[Route("video/categoria/{categoria}/{page?}/{sort?}")]
public async Task<ActionResult> Index(string categoria, int? page, string sort)
{
...  
}

My RouteConfig.cs:

public static void RegisterRoutes(RouteCollection routes)
{
  routes.IgnoreRoute("{resource}.axd/{*pathInfo}");

  routes.MapMvcAttributeRoutes();

  routes.MapRoute(
    name: "Default",
    url: "{controller}/{action}/{id}",
    defaults: new { controller = "Categoria", action = "Index", id = UrlParameter.Optional }
  );

}

My URL.Action:

Url.Action("Index","Video", new { categoria = @Request.QueryString["categoria"], page = 5, sort = ViewBag.CurrentSort})

Result of URL.Action: http://localhost:59278/Video?categoria=desenho&page=4

Expected result of Url.Action: http://localhost:59278/video/categoria/desenho/4

My Html.ActionLink:

@Html.ActionLink("Teste", "Index", "Video", new { categoria = @Request.QueryString["categoria"], page = 1, sort = "teste" }, null))

Html.ActionLink Result:

http://localhost:59278/Video?categoria=desenho&page=1&sort=teste

Expected result in Html.ActionLink:

http://localhost:59278/video/categoria/desenho/1/teste

How do you turn the result into the expected result?

UPDATE

It works the following were:

@Html.ActionLink("Teste", "Index", "Video", new { categoria = 1, page = 1, sort = 1 }, null)

So I believe that reducing the margin of places where the problem might be to the fourth parameter of the constructor.

UPDATE

After checking new possibilities I saw that the problem is @Request.QueryString["categoria"] , when used it does not do the URL correctly, but when I take it out and play a string or int in place it works normally.

What is the reason for this?

UPDATE

Another attempt did not work, but I discovered that you can not actually use any variables in the parameter:

@{ 
    var cat = @Request.QueryString["categoria"];
}

@Html.ActionLink("Teste", "ConsultaVideo", "Video", new { categoria = cat, page = 1, sort = "teste" }, null)
    
asked by anonymous 07.11.2015 / 02:05

2 answers

1

After many tests I found the solution.

The problem is that @Request.QueryString["categoria"] returns null, so the constructor category object receives null and with that it understands that there is no category in the route, so it does not find the method in the control.

I do not know how to get value, that would be the subject of another question.

The code I used for testing is this:

    
07.11.2015 / 17:09
2

Apparently everything is fine, just use RouteData.Values to retrieve the value of when instead of Request .

Your variable would then be cat :

var cat = @ViewContext.RouteData.Values["categoria"];

Any questions, this answer can help you better.

    
09.11.2015 / 14:08