Reputation: 2488
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.
Upvotes: 0
Views: 699
Reputation: 6423
id by default is going to be passed in the url. You create the url with whatever id is passed with this line
var url = "@Url.Action("Product", "Product")/" + id;
if you are getting the current id in the url then that is what you are passing to that method. If you want to get the url without the id just remove that part
var url = "@Url.Action("Product", "Product")";
the replace you linked is very useful for passing information from the script to the action you are calling. Great way to combine MVC and javascript
Upvotes: 1
Reputation: 69973
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.
Upvotes: 2