Asp.net MVC Routelink空控制器参数

时间:2015-06-09 18:11:09

标签: c# asp.net asp.net-mvc asp.net-mvc-4 routing

我有两条路线,默认路线

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

我添加了另一条路线,有时参数会用字符串

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

当我使用" ByName"在RouteLink中路由,URL很好,但我的控制器中的参数是空的

在视图中:

@Html.RouteLink(application.Nom, "ByName", new {controller= "Packaging", action = "EditApplication", name = application.Nom})

控制器

public ActionResult EditApplication(string name)

网址结果很好:... / Packaging / EditApplication / VisualStudio,但参数值保持为null。为什么呢?

谢谢

1 个答案:

答案 0 :(得分:1)

您不能拥有TWO具有相同参数和相同定义的路由,第一个路线优先。相反,您需要在路线中使用特定约束来显示如下所示的内容。

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

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