如何从一个控制器操作方法路由到另一个控制器操作方法而不在MVC 5中显示控制器名称

时间:2016-11-01 05:00:24

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

我在Route.config中有两个不同的MapRoutes,如下所示......

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

routes.MapRoute(
    name: "SubjectRoute",
    url: "{action}", 
    defaults: new { controller = "Subjects", action = "Subjects" }
);

和我的@HTML.ActionLinkIndex

中的IndexController操作方法中如下所示
@Html.ActionLink("SUBJECTS", "Subjects","Subjects", new { }, new { @class = "text" })

现在当我点击索引操作方法中的SUBJECTS链接时,它应该转到主题控制器中的主题操作,而不显示URL中的控制器名称。

如何做到这一点?

1 个答案:

答案 0 :(得分:0)

routes.MapRoute(
    name: "SubjectRoute",
    url: "Subjects", 
    defaults: new { controller = "Subjects", action = "Subjects" }
);

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

通过上述内容,调用

@Html.ActionLink("SUBJECTS", "Subjects","Subjects", new { }, new { @class = "text" })

应生成

/Subjects

默认且更通用的路由现在将捕获所有其他请求并将它们路由到IndexController,现在它充当站点根目录/索引。

例如假设

public class IndexController : Controller {
    public ActionResult Index() {...}
    public ActionResult ContactUs() {...}
    public ActionResult About() {...}
}

基于上述控制器的可用路线

/
/Index
/ContactUs
/About