N
N
Nikita2014-06-10 12:53:18
ASP.NET
Nikita, 2014-06-10 12:53:18

What is causing the strange behavior of Url.Action in asp.net mvc 4?

Especially for the purity of the experiment, I created a new asp.net mvc 4 application.
Routes :

//more detail route
routes.MapRoute(
            name: "{lang}/category/{category}",
            url: "{lang}/category/{category}",                
            defaults: new { controller = "Home", action = "Index" }
        );
        //more general route
        routes.MapRoute(
            name: "{lang}",
            url: "{lang}",

            defaults: new { controller = "Home", action = "Index"  }
        );

HomeController :
[HttpGet]
public ActionResult Index(string category)
{
   return View("~/Views/Home/index.cshtml");
}

On view :
Url.Action("Index","Home", new {lang="en"});
And now the question is why on any page Url.Action generates "/en" in html (as intended), but on the page "/en/category/1" - the same Url.Action generates "/en" /category/1"?
It looks like the category route value is leaking from the url to the Url.Action generation.
Does the route data from the URL somehow affect the generation of the routes themselves? Maybe someone who has come across or can point to a useful link with an explanation of this behavior - I will be grateful.
ps. I decided through Action.RouteUrl and specifying the desired route by name, but this does not remove the issue.
Update : stackoverflow.com/questions/20349681/urlhelper-act...
after all, this is by design, when generating the url, the current route data from the Request is also taken into account.

Answer the question

In order to leave comments, you need to log in

1 answer(s)
V
Vasily, 2014-06-10
@vassav

swap routes:

//more general route
        routes.MapRoute(
            name: "{lang}",
            url: "{lang}",

            defaults: new { controller = "Home", action = "Index"  }
        );
        routes.MapRoute(
            name: "{lang}/category/{category}",
            url: "{lang}/category/{category}",                
            defaults: new { controller = "Home", action = "Index" }
        );

Didn't find what you were looking for?

Ask your question

Ask a Question

731 491 924 answers to any question