Question

I have a controller named DummyController when i call the controller it is like DummyController/Index i want this controller to be called as maincontroller/dummycontroller/index where mainController is a different controller altogether.

Code for DummyController:

  public ActionResult Index()
            {
                return View("~/Views/main/dummy/index.cshtml",db.Users.ToList());
            }

the location of index file of Dummy Controller is main/dummy

Now the problem is when I call the dummy controller's index page i get the url as dummy/index i want the url to be displayed as main/dummy/index.

Is there any way to create child controllers? o change the url only for the specific controller

Was it helpful?

Solution

This was relatively straightforward, once I got past a simple issue.

By using a combination of [RoutePrefix("")] & [Route("")] on my controller, I was able to make this work. Attribute Routing requires a call to routes.MapMvcAttributeRoutes() in your Global.asax.cs RegisterRoutes() method.

    [RoutePrefix("main/dummy")]
    [Route("{action=index}/{id:long?}")]
  • {action=index} defines the action handling for the route, and specifies /index as the default action, if it's not supplied (ie, ~/main/dummy/ will render ~/main/dummy/index
  • {id:long?} specifies the id route attribute
    • :long is the syntax for constraining the param to the long datatype
    • ? denotes this param is optional. (more on this here)

This could also be done using the standard MapRoute() technique:

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


I forgot to add what my simple issue was.. I had 2 actions in the controller: Index() and Index(id), which would always result in the AmbiguousRouteException, and was leading me to believe my Route was defined incorrectly. Changing that to View(id) solved it. (I guess technically the route was wrong, but I didn't need to spend any more time trying to make it work that way)

Licensed under: CC-BY-SA with attribution
Not affiliated with StackOverflow
scroll top