我們擁有一個具有不同區域的MVC應用程序。此時只有一個區域被註冊(在config中定義),並且在區域註冊中不進行路由註冊。我遇到了路由問題,因爲Url.Action方法停止工作。我的簡化RouteConfig看起來是這樣的:MVC5 Url.Action在區域內返回null
routes.MapRoute(
name: "Second",
url: "second/{action}/{id}",
defaults: new { controller = "Second", action = "Action", id = UrlParameter.Optional },
namespaces: new[] { "MvcApplication1.Areas.MyArea.Controllers" }
).DataTokens["area"] = "MyArea";
routes.MapRoute(
name: "Home",
url: "home/{action}/{id}",
defaults: new { controller = "Home", action = "Index", id = UrlParameter.Optional },
namespaces: new[] { "MvcApplication1.Controllers" }
);
routes.MapRoute(
name: "Default",
url: "{controller}/{action}/{id}",
defaults: new { controller = "Home", action = "Index", id = UrlParameter.Optional },
namespaces: new[] { "MvcApplication1.Controllers" }
);
的問題是,當我嘗試調用@Url.Action("Index", "Home")
內Action.cshtml在第二控制器MyArea返回null。當我在Home控制器的Index.cshtml中調用它時,它運行良好。我已經發現,當我在Action.cshtml中使用@Url.Action("Index", "Home", new {Area = ""})
時,它工作得很好,但是爲什麼會發生這種情況?我怎樣才能避免只能撥打@Url.Action("Index", "Home")
沒有路由值?