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

Asked

Viewed 1,205 times

1

I have the following method in 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.Action URL:

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

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

Expected Url.Action result: 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 output:

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

Expected result in Html.Actionlink:

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

How to turn the result into the expected result?

UPDATING

It works from 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 could be to the fourth parameter of the constructor.

UPDATING

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

What is the reason for this?

UPDATING

Another attempt, it didn’t work, but I found that actually you can’t use any variable in the parameter:

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

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

2 answers

2

Apparently it’s all right, just use the Routedata.Values to recover the value of instead of Request.

Would that be your variable cat:

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

Any doubt, that answer can help you better.

1


After many tests I found the solution.

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

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

The code I used for testing is this:

Browser other questions tagged

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