• Working with ambigious controller names in MVC3

    by Venkata Koppaka | Apr 30, 2011

    If you are working with ASP.NET MVC2 or above you might want to have same controller name across multiple areas. For example you might have an Home Controller on your root of your website and also a Home Controller on the Admin Area of your website. Looks like a a reasonable thing to have

     

    But if you run your application you will have an error saying "Multiple Types were found that match the controller..." or like the screenshot below

     

    To overcome this error you need register a route specific to the area with the namespace. Use the code snippet below-

    public static void RegisterRoutes(RouteCollection routes) 
            { 
                routes.IgnoreRoute("{resource}.axd/{*pathInfo}"); 
     
                //General Route 
                routes.MapRoute( 
                    "Default", // Route name 
                    "{controller}/{action}/{id}", // URL with parameters 
                    new { controller = "Home", action = "Index", id = UrlParameter.Optional }, // Parameter defaults 
                    new string[] { "AmbiguousControllers.Controllers" } 
                ); 
     
                //Route for Admin Area 
                routes.MapRoute( 
                    "Admin Default", // Route name 
                    "{controller}/{action}/{id}", // URL with parameters 
                    new { area = "Admin", controller = "Home", action = "Index", id = UrlParameter.Optional }, // Parameter defaults 
                    new string[] { "AmbiguousControllers.Areas.Admin.Controllers" } 
                ); 
     
            } 

    And now you can have multiple controllers with the same name.

     Hope this helps,

    Cheers

    Venkata

    Go comment!