0
votes

I have an MVC4 app with a Companies Area.

Given file structure:

Areas   
\
  Companies
    \
     Controllers
       |
       DefaultController (Contains Index and Edit actions)
       TestController (Contains Index and Test action)

I want my URL's to be like:

  • /Companies
  • /Companies/Edit
  • /Companies/Test
  • /Companies/Test/Test

My route is set like like in my CompaniesAreaRegistration class.

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

Results:

  • /Companies - Works
  • /Companies/Edit - 404
  • /Companies/Default/Edit - Works
  • /Companies/Test - Works
  • /Companies/Test/Test - Works

How can I access my DefaultController.Edit() action without "Default" in the URL?

Update

Based on Brad's answer, I know I can hard code the paths like this and it will work. I was really hoping for more of an automatic solution. I don't know how many actions I will end up having on some Area's default controllers. I don't want to have to create a new route for every one.

This is the default route added as part of the MVC template in the App_Start/RouteConfig.cs file.

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

If I have an action on the HomeController called "Test", I can hit that action using the URL /Test. I don't have to add a new route with the URL like "/Test/{id}" in order for this to work. It appears to ignore the {controller} part of the URL and use the default controller configuration.

Why does this behavior change when you do it in an Area?

The Area route is exactly the same as the Default route, except for the "Companies/" prefix to the URL.

As a test, I changed my Default route URL to url: "Example/{controller}/{action}/{id}" and I am still able to access HomeController.Test() by at the URL /Example/Test.

1

1 Answers

2
votes

Using:

context.MapRoute(
    name: "Companies_Edit",
    url: "Companies/Edit/{id}",
    defaults: new { controller = "Default", action = "Edit", id = UrlParameter.Optional }
);

Remember parameters are filled left-to-right (can't skip over {controller} and only populate {action}. If you want {controller} to be assumed, specify it in the defaults)