Search code examples
asp.net-mvcroutesarea

Mvc area routing?


My project structure:

Controller
    AdminController
    HomeController

After Area addition my project structureI added an Admin area to project,

Areas
    Admin
        Controller
            SomeController
Controller
    AdminController
    HomeController

then all links are broken. For example

@Html.ActionLink(
    "go to some action", 
    "SomeAction", 
    "Admin", 
    new { area = "" }, 
    null)

When I write above link, it routes me to www.myDomain.com/Admin/SomeAction, but this is Area action, I want to route to AdminController action.

How can I do this? Should I change Area or Controller name?

Update

above link output:

domain/Admin/SomeAction
// I expect that is AdminController/SomeAction
// but not. There is SomeAction in my admin controller
// I get this error "The resource cannot be found."
// because it looks my expected, but it works unexpected
// it tries to call AdminArea/SomeController/SomeAction

Update 2

for example:

 @Html.ActionLink(
    "go to some action", 
    "SomeAnotherAction", 
    "Admin", 
    new { area = "" }, 
    null)

for above link I dont get any error, because I have a SomeAnotherAction in my area.

Area registeration

public override void RegisterArea(AreaRegistrationContext context)
{
    context.MapRoute(
        "Admin_default",
        "Admin/{controller}/{action}/{id}",
        new { action = "Index", id = UrlParameter.Optional }
    );
}

Thanks...


Solution

  • Since you have registered your areas first, they are taking precedence. There's no easy way around this. The best solution would be to rename your AccountController in the main part of the site to something else in order to avoid the conflict.

    Another possibility is to constrain the controllers in your Area route registration:

    context.MapRoute(
        "Admin_default",
        "Admin/{controller}/{action}/{id}",
        new { action = "Index", id = UrlParameter.Optional },
        new { controller = "Some|SomeOther" }
    );
    

    Now only requests to /Admin/Some/{action} or /Admin/SomeOther/{action} will be routed to the area, meaning that /Admin/SomeAction will be intercepted by the global route definition and routed to your AdminController.