Url.Action假设其他RouteValue

时间:2013-08-02 03:07:21

标签: c# asp.net-mvc

我有一个包含以下javascript的部分页面:

var url = '@Url.Action("Details", "Users", null)/' + userID;

除了具有url结构的页面外,每个页面都可以正常工作:

/Site/Users/Details/{ID}

例如,当ID = 25时,asp.net将输出:

var url = '/Site/Users/Details/25/' + userID;

但它应该是:

var url = '/Site/Users/Details/' + userID;

如何阻止@Url.Action假设这个额外的路线值?

修改

我的路线包含默认路线配置......

public static void RegisterRoutes(RouteCollection routes)
{
    routes.IgnoreRoute("{resource}.axd/{*pathInfo}");

    routes.MapRoute(
        name: "Default",
        url: "{controller}/{action}/{id}",
        defaults: new { controller = "Home", action = "Index", id = UrlParameter.Optional }
    );
}

3 个答案:

答案 0 :(得分:2)

尝试这样的事情

var url = '@Url.Action("Details", "Users", new { id = -1})'; //Render Url with -1 value
url = url.replace(-1, userID); //replace -1 with userId

答案 1 :(得分:0)

为什么不在Url Action方法的路由值中包含id?

var url = '@Url.Action("Details", "Users", new {id = userID})';

答案 2 :(得分:0)

也许尝试类似的事情:

var urlString = Url.Action("Details", "Users", null, "http");
var uri = new Uri(urlString);

并在javascript中:

var url = '@uri.AbsolutePath' + '/' + userID;