在 EuroController 的 Index.cshtml 视图中,我有一个 ActionLink ,我想使用Euro控制器的“IndexByYear”操作:
@Html.ActionLink("Year 2006", "IndexByYear","Euro", new { id = "", year = 2006 }, null)
但问题是它会转到Index()方法,即使它是在 RouteConfig 上设置的所有东西:
routes.MapRoute(
name: "Default",
url: "{controller}/{id}",
defaults: new { controller = "Home", action = "Index", id = UrlParameter.Optional }
);
routes.MapRoute(
name: "Euro",
url: "{controller}/{year}/{id}",
defaults: new { controller = "Euro", action = "IndexByYear", year = DateTime.Now.Year, id = UrlParameter.Optional }
);
这是 EuroController :
public ActionResult Index(int? id)
{
...
}
public ActionResult IndexByYear(int? id, int year)
{
...
}
这也不起作用,因为它也适用于Index()方法:
@Html.RouteLink("Ano 2006","Euro",new { id = "", year = 2006 },null)
如果我手动导航到 domain / Euro / 2016/1 ,那么它会使用正确的路线。似乎没有参数,它通过默认路线。
我的问题是,为什么ActionLink不使用指定的IndexByYear,或者RouteLink使用指定的默认(欧元)路由?
答案 0 :(得分:0)
如果你希望只是,那么EuroController会有一个"特殊的"路由,您可能希望执行以下操作:
routes.MapRoute(
name: "Euro",
url: "euro/{year}/{id}",
defaults: new { controller = "Euro", action = "IndexByYear", year = DateTime.Now.Year, id = UrlParameter.Optional }
);
routes.MapRoute(
name: "DefaultNoController",
url: "{action}/{id}",
defaults: new { controller = "Home", action = "Index", id = UrlParameter.Optional },
constraints: new { isMethodInHomeController = new RootRouteConstraint<Controllers.HomeController>() }
);
routes.MapRoute(
name: "Default",
url: "{controller}/{action}/{id}",
defaults: new { controller = "Home", action = "Index", id = UrlParameter.Optional }
);
约束的定义如下:
public class RootRouteConstraint<T> : IRouteConstraint
{
public bool Match(HttpContextBase httpContext, Route route, string parameterName, RouteValueDictionary values, RouteDirection routeDirection)
{
var rootMethodNames = typeof(T).GetMethods().Select(x => x.Name.ToLower());
return rootMethodNames.Contains(values["action"].ToString().ToLower());
}
}
这将匹配
domain/euro/1
到EuroController上的Index操作domain/euro/2008/1
到EuroController上的IndexByYear操作domain/
到HomeController上的Index操作domain/about
到HomeController上的About操作domain/someothercontroller
到您定义的其他控制器上的Index操作您可能需要阅读https://msdn.microsoft.com/en-us/library/cc668201.aspx和https://www.asp.net/mvc/overview/older-versions-1/controllers-and-routing/creating-a-custom-route-constraint-cs