Search code examples
asp.net-mvcasp.net-mvc-4razorurl-action

Url.Action, Where does the parameter come from


I have this javascript code in the view:

function getUrl(id) {
    var url = "@Url.Action("Product", "Product")/" + id;
    return url;
}

and this is the routing config:

routes.IgnoreRoute("{resource}.axd/{*pathInfo}");

routes.MapRoute(
    name: "localized",
    url: "{culture}/{controller}/{action}/{id}/{title}",
    defaults: new { culture = "en", controller = "Home", action = "Index",
         id = UrlParameter.Optional, title = UrlParameter.Optional},
    constraints: new { culture = "en|fa" }
            );

What I'm expecting from Url.Action("Product", "Product") is to return /en/Product/Product/ but what I got is /en/Product/Product/92 and 92 is the id of the current product and I'm trying to create the url for the next product. I could find a workaround thanks to this answer's replace trick, but now I just want to know why this is happening.


Solution

  • Url.Action will include the current route values if you don't specify them.

    Try this instead

    @Url.Action("Product", "Product", new { id = UrlParameter.Optional })/" + id;
    

    Or you could set the id to null in the Url.Action call to clear it and then append the id to the end.