在Global.asax中注册RegisterRoutes

时间:2015-02-04 21:36:57

标签: c# asp.net asp.net-mvc asp.net-mvc-3

我完全不了解RegisterRoutes。让我们假设浏览器的当前URL是

//Home/ListCompanies/{filter}
http://localhost:21047/Home/ListProducers/Yerli

我们通过以下链接来到上面的地址

@Html.ActionLink("Yerli Markalar", "ListProducers/Yerli", "Home")

我在当前页面上有一个链接,如下所示

@Html.ActionLink("Bayiler", "ListCompanies", "Home")
http://localhost:21047/Home/ListCompanies/Yerli

但是当我将鼠标悬停在最后一个链接上时,它会显示“Yerli”过滤器,我不会在链接中显示它

为什么过滤器“Yerli”来到这里?它应该看起来像

http://localhost:21047/Home/ListCompanies/

我做错了什么?

这是我的路线

routes.MapRoute(
            null,
            "Home/ListProducers/{filter}", // Route name
            new { controller = "Home", action = "ListProducers", filter = UrlParameter.Optional } // Parameter defaults
        );


 routes.MapRoute(
            null,
            "Home/ListCompanies/{filter}", // Route name
            new { controller = "Home", action = "ListCompanies", filter = UrlParameter.Optional } // Parameter defaults
        );

1 个答案:

答案 0 :(得分:2)

首先,你不要使用

@Html.ActionLink("Yerli Markalar", "ListProducers/Yerli", "Home")

如果" Yerli"是要传递给

的参数
public ActionResult ListProducers(string filter)

然后它需要

@Html.ActionLink("Yerli Markalar", "ListProducers", "Home", new { filter = "Yerli" }, null)

将生成..../Home/ListCompanies/Yerli

您的问题是您已将action参数生成为ListCompanies/Yerli,而它应为ListCompanies

请注意,您还应该为路线命名

routes.MapRoute(
  "ListProducers", // name it!
  "Home/ListProducers/{filter}", // Route name
   new { controller = "Home", action = "ListProducers", filter = UrlParameter.Optional } // Parameter defaults
);

然而,这些路线似乎是不必要的,您可以删除它们并让默认路线处理它

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

只需将方法更改为

即可
public ActionResult ListProducers(string id)

并使用

@Html.ActionLink("Yerli Markalar", "ListProducers", "Home", new { id = "Yerli" }, null)

将产生完全相同的结果