URL.Action和Html.ActionLink生成的URL不正确

时间:2011-09-26 14:12:21

标签: asp.net-mvc-3 routes

我有路线:

routes.MapRoute(
    "NewsRoute",
    "News/{newsId}/{newsTitle}",
    new {
        controller = "News",
        action = "News",
        newsId = UrlParameter.Optional,
        newsTitle = UrlParameter.Optional
    }
);
routes.MapRoute(
    "Default", // Route name
    "{controller}/{action}/{id}", // URL with parameters
    new { controller = "Home", action = "Home", id = UrlParameter.Optional } // Parameter defaults
);

和用法:

@Url.Action("News", "News", new { newsId = "", newsTitle = "" })

我希望拥有“/ News”网址,而是生成“/ News / News”。我猜是使用默认路由。 所以问题是为什么跳过NewsRoute?

1 个答案:

答案 0 :(得分:1)

解决方案是将具有2个可选参数和操作的路线拆分为两个单独的操作:

routes.MapRoute(
    "NewsRoute",
    "News", new {
        controller = "News",
        action = "Index"
    }
);

routes.MapRoute(
    "Specific News",
    "News/{id}/{title}",
    new {
        controller = "News",
        action = "News",
        title = UrlParameter.Optional
    }
);