0

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.

4

2 回答 2

2

Url.Action如果您不指定它们,将包括当前路由值。

试试这个

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

或者您可以id在调用中将其设置为 nullUrl.Action以清除它,然后将 id 附加到末尾。

于 2014-02-03T17:18:21.693 回答
1

默认情况下,id 将在 url 中传递。您使用此行传递的任何 id 创建 url

var url = "@Url.Action("Product", "Product")/" + id;

如果您在 url 中获取当前 id,那么这就是您传递给该方法的内容。如果您想获取没有 id 的 url,只需删除该部分

var url = "@Url.Action("Product", "Product")";

您链接的替换对于将信息从脚本传递到您正在调用的操作非常有用。结合 MVC 和 javascript 的好方法

于 2014-02-03T17:18:43.430 回答