Reputation: 19449
the default routing works fine
mysite.com/home/about
and i even see how to customize it to make it shorter
so i can say:
mysite.com/edit/1 instead of mysite.com/home/edit/1
but how can i make it longer to handle url like the following
mysite.com/admin/user/1 // works
mysite.com/admin/user/details // does not work
mysite.com/admin/question/create // does not work
i cant just treat the id as an action? i need a custom route?
do i need to create new controllers for each table or can i route them all through the Admin controller
thanks a lot
Upvotes: 3
Views: 205
Reputation: 753
As has been mentioned already, probably your best bet would be to use the new Areas feature
You can achieve this type of routing without Areas, but as the number of controllers gets large the maintainability of your site will diminish. Essentially what you do is to hard-code the controller name into the Route definition which means that you have to add new route mappings for each new Admin controller. Here's a few examples of how you might want to set up your routes without Areas.
routes.MapRoute("AdminQuestions", // Route name
"admin/question/{action}/{id}", // URL with parameters
new { controller = "AdminQuestion", action = "Index" } // Parameter defaults
);
routes.MapRoute("AdminUsers", // Route name
"admin/user/{action}/{id}", // URL with parameters
new { controller = "AdminUser", action = "Index" } // Parameter defaults
);
Alternatively you could route everything through the Admin controller, but it would quickly become very messy with your controller actions performing multiple roles.
routes.MapRoute("Admin", // Route name
"admin/{action}/{type}/{id}", // URL with parameters
new { controller = "Admin", action = "Index" } // Parameter defaults
);
With your AdminController action(s) looking like:
public virtual ActionResult Create(string type, int id)
{
switch (type)
{
case 'question':
// switch/case is code smell
break;
case 'user':
// switch/case is code smell
break;
// etc
}
}
Upvotes: 2
Reputation: 1095
Adding routes to global.asax is fairly straight forward. Put the more specific routes above the more general routes. The most typical pattern is controller/action/parameter/parameter... If you need something more complex, you may want to look at MVC Areas.In you example above "mysite.com/admin/user/details" is looking for a controller named "admin" and an action named "user", with everything after that being parameter on the action method (assuming a typical route setup)
Upvotes: 1