Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

ASP.NET MVC 3 Controller route - make everything under home controller appear under the domain

Currently everything under homecontroller appears in the URL as

example.com/Home/{Action}

Is there a way we can keep all other routing the way it is but ONLY special case home controller so everything under home comes under the domain.

like

example.com/about
example.com/contact
example.com/error

instead of creating new controller classes for each of them.

EDIT:

The other URL's like

example.com/user/details/123
example.com/user/edit/123

Which are in the userController should work the same as they are now

like image 883
MoXplod Avatar asked Sep 07 '11 22:09

MoXplod


1 Answers

I think the best way is:

 routes.MapRoute("home", "home", new { controller = "Home", action = "Index" });
 routes.MapRoute("about", "about", new { controller = "Home", action = "About" });
 routes.MapRoute("contact", "contact", new { controller = "Home", action = "Contact" });

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

and when you want to create a link, use:

@Html.RouteLink("Home", "home", new{/* route values */}, new {/* html attribues */})

OR:

@Html.RouteLink("Home", "home")

instead of:

@Html.ActionLink("Home", "Index", "Home", new{/* route values */}, new {/* html attribues */})

this works for me, and should work for you too.

UPDATE:

you can create a symbol like @ (or - or anything else), before the action part in url, to make the url unique, such as:

routes.MapRoute(
    "test",  // route name
    "@{action}", // url and parameters
    new {controller = "MyHome", action = "Home"} // parameter defaults
    );
routes.MapRoute(
    "Default", // Route name
    "{controller}/{action}/{id}", // URL with parameters
    new { controller = "Home", action = "Index", id = UrlParameter.Optional } // Parameter defaults
     );

in this way, your urls are different from the Default map-route and you can create urls like:

site.com/@Home
site.com/@About
site.com/@Contact

but the first, in my idea, is better and I always use that.

like image 56
amiry jd Avatar answered Oct 25 '22 07:10

amiry jd