如何从View调用MVC路由

时间:2014-11-14 18:10:48

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

我遇到了在当前网址上添加网址的问题,例如: Localhost / Config - >本地主机/配置/简介 通过调用@ Html.ActionLink(Resources.General.Achievements," Index"," Profile")

当我真正想要的是:Localhost / Profile

我知道这可以使用MVC路由,我只是无法弄清楚如何从View中调用它们。我使用过Html.BeginRouteForm,但这条路线在提交时不会被触发。

这是我的路线配置

routes.MapRoute(
            name: "Profile",
            url: "Profile/{id}",
            defaults: new { controller = "Profile", action = "Index" },
            namespaces: new[] { "Cobalt.Controllers" }
            );

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

我正在尝试访问根目录中的Profile控制器和Index操作。我有Config和Manage Areas,我试图在根目录中回调控制器时逃避。

提前感谢您提供任何帮助

2 个答案:

答案 0 :(得分:1)

使用RouteLink

@Html.RouteLink(Resources.General.Achievements, "Profile", new { id = "1234" })

请注意,由于您的“id”参数未在Profile路由中声明为可选,因此除非您提供,否则它将不匹配。

答案 1 :(得分:1)

在处理区域时,如果要从一个区域移动到另一个区域或从一个区域移动到根区域,可以使用ActionLink的重载,它允许您指定路径数据并传递空字符串(或者适当的区域名称)到区域:

@Html.ActionLink(Resources.General.Achievements, "Index", "Profile", new { area = string.Empty })