A Bogus
A Bogus

Reputation: 3930

Default to Area Controller

For an ASP.NET MVC application, I have 2 controllers with the name Home. One of the controllers is in an Areas section, one is not. If someone goes to the base path /, I am trying to default to the controller in the Areas section. I am under the impression that this is possible. I have the following setup which I believe is supposed to make that happen -

enter image description here

When I go to /, I am still taken to the Controller in MVCArea01/Controllers/ and not MVCArea01/Areas/Admin/Controllers/.

(in case the code in the image is too small to see, here is the code for the method, RegisterRoutes)

public static void RegisterRoutes(RouteCollection routes)
{
    routes.IgnoreRoute("{resource}.axd/{*pathInfo}");

    routes.MapRoute(
        "Default", // Route name
        "{controller}/{action}/{id}", // URL with parameters
        new { controller = "Home", action = "Index", id = UrlParameter.Optional }, // Parameter defaults
        new[] {"MVCAreas01.Areas.Admin.Controllers"}  // I believe this code should cause "/" to go to the Areas section by default
    );

}

What is the correct solution?

Upvotes: 2

Views: 657

Answers (3)

kbvishnu
kbvishnu

Reputation: 15650

@ABogus

I modified the AdminAreaRegistration.cs file. Refer the image below

Modified the MapRoute

Also I modified the Route.config as below.

Route.config is also modified.

I got the output as like this

Default route to Areas->Admin->Controller->Home

You can download the sample project from https://www.dropbox.com/s/o8in2389e8aebak/SOMVC.zip

Upvotes: 0

Adas Petrovas
Adas Petrovas

Reputation: 575

You should create additional route for your starting page, that will direct processing to the right controller:

public static void RegisterRoutes(RouteCollection routes)
{
    routes.IgnoreRoute("{resource}.axd/{*pathInfo}");

    routes.MapRoute(
        "Home_Default",
        "",
        new { controller = "Home", action = "Index", id = UrlParameter.Optional },
        new[] { "MVCAreas01.Areas.Admin.Controllers" });

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

Upvotes: 0

Paul Fleming
Paul Fleming

Reputation: 24526

public static void RegisterRoutes(RouteCollection routes)
{
    routes.IgnoreRoute("{resource}.axd/{*pathInfo}");

    routes.MapRoute(
        "Default", // Route name
        "{controller}/{action}/{id}", // URL with parameters
        new { 
            controller = "Home", 
            action = "Index", 
            id = UrlParameter.Optional, 
            area = "Admin" 
       }
}

Upvotes: 1

Related Questions