简体   繁体   中英

How to route from one controller action method to another controller action method without displaying controller name in MVC 5

I have two different MapRoutes in Route.config as follows...

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" }
);

and my @HTML.ActionLink is as follows in Index action method which is in IndexController

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

Now when I click on SUBJECTS link in Index action method, it should go to Subjects action in Subjects controller with out displaying controller name in the URL.

How can this be done?

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 }
);

With the above, calls to

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

should generate

/Subjects

The default and more general route will now catch all other requests and route them to the IndexController which now acts as the site root/index.

for example assuming

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

the available routes based on above controller are

/
/Index
/ContactUs
/About

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM