MVC路由配置:具有不同路由名称的多个路由

时间:2016-01-17 12:16:37

标签: asp.net-mvc routing asp.net-mvc-5

我在MVC中创建了多条路径名不同的路由。

routes.MapRoute(
    name: "PostDetails",
    url: "Ad/{id}/{item}",
    defaults: new { controller = "Home", action = "Post" }
);

我正在从javascript函数调用路由以重定向到此路由

var url = '@Url.RouteUrl("PostDetails", new { id = "_id_", item = "_name_" })';     
url = url.replace("_id_", id).replace("_name_", name);
window.location.href = url;

这是404的错误。

1 个答案:

答案 0 :(得分:2)

您必须在RouteConfig中的默认路线之前添加您的路线,如:

public static void RegisterRoutes(RouteCollection routes)
{
        routes.IgnoreRoute("{resource}.axd/{*pathInfo}");
        routes.MapRoute(
            name: "PostDetails",
            url: "Ad/{id}/{item}",
            defaults: new { controller = "Home", action = "Post" }
        );
        routes.MapRoute(
            name: "Default",
            url: "{controller}/{action}/{id}",
            defaults: new { controller = "Home", action = "Index", id = UrlParameter.Optional }
        );
}