我有以下一条路线,在我的global.asax中注册。

routes.MapRoute(
    "Home", // Unique name
    "", // Root url
    new { controller = "Home", action = "Index", 
        tag = string.Empty, page = 1 }
);

KEWL。当我启动网站时,它正确地选择了这条路线。

现在,当我尝试以编程方式执行以下操作时,它将返回NULL。

var pageLinkValueDictionary = 
    new RouteValueDictionar(linkWithoutPageValuesDictionary)
        {{"page", 2}};

VirtualPathData virtualPathData = 
    RouteTable.Routes.GetVirtualPath(viewContext, "Home"
        pageLinkValueDictionary);

// NOTE: pageLinkValueDictionary == 
//     Key: Action, Value: Index; Key: page, Value: 2

为什么会这样?

我的印象是它会找到Home路由,但是附加了未找到的任何值作为查询字符串项?

更新

这仍然没有运气。此外,使用 MVC RC ,我现在需要将viewContext更改为veiwContext.RequestContext ..它编译但我仍然得到一个null结果。

更新2

当我的路线没有 page = 1 默认项目时,路线 IS FOUND 。 例如

routes.MapRoute(
        "Home",
        "",
        new { controller = "Post", action = "Index", tags = string.Empty }
    );

..和 RouteTable.Routes.GetVirtualPath 返回 VirtualPathData 实例。当我重新添加 page = 1 (默认值)时,返回的 VirtualPathData 实例是否为空?

有帮助吗?

解决方案

它返回null的原因是因为没有带有“page”的路由。路线数据。

你可以稍微扩展一下你想要实现的目标吗?如果您想重定向到包含url / page / 2或/?page = 2的页面,那么您应该使用RedirectToRoute或RedirectToAction:

return RedirectToRoute("IndexDefault", new {page = "2"}); 

其他提示

我认为你的路线应该是这样的:

route.MapRoute("theRoute", "{controller}/{action}/{tag}/{page}",
  new { controller="Post", action="Index", tag="", page=1 });

或(取决于完整网址应该是什么样的)......

route.MapRoute("theRoute", "/{tag}/{page}",
  new { controller="Post", action="Index", tag="", page=1 });

这仍然符合 http://mysite.com/ 的请求并转到您的默认路线值定义如上。但是现在当你指定标签或页面时,你会得到你想要的网址。

你应该看看菲尔的路线测试员:

ASP.NET路由调试程序

许可以下: CC-BY-SA归因
不隶属于 StackOverflow
scroll top