views:

194

answers:

1

Hi, I'm working on an MVC application and I have and admin area... So what I need is:

When user makes request to admin (for example "/Admin/Post/Add") I need to map this to controller AdminPost and action Add... is it possible?

+2  A: 

If your controller is named AdminPostController and you want it to map to '/Admin/Post/Add' then you can use:

routes.MapRoute("Admin",  // Route name
  "Admin/Post/{action}/{id}",  // URL with parameters
  new { controller = "AdminPost", action = "Add", id = "" }  // Parameter defaults
);

Note the use of the parameter defaults.

If your controller is named AdminController and you just wanted to separate the request method then use the default:

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

Which will map '/Admin/Add/' to the controller:

public class AdminController : Controller {

  [AcceptVerbs(HttpVerbs.Post)]
  public ActionResult Add(int id) {
    //...
  }

  [AcceptVerbs(HttpVerbs.Get)]
  public ActionResult Add(int id) {
    //...
  }

}

Note the use of [AcceptVerbs] to identify which method to invoke for POST requests and GET requests.

See Scott Gu's blog for more details

David G
Yeah, but i meant it like: If I have url /Admin/XXX/YYY/Z, is it possible to map to controller "AdminXXX"?
You can. But you have to do it manually. So you'd have one mapping for /Admin/XXX -> AdminXXX and one mapping for Admin/111 -> Admin111 .
James S
Thanks, I was kinda hoping it could be done automatically, but neverminds. Thanks for your answers :-)
Well... if you only have one controller named Post, then it can be done automatically, no way to combine {part1}/{part2} into a single controller name. HOWEVER... you can differentiate by namespaces. You should look at "areas". e.g. MVC 2 or http://haacked.com/archive/2008/11/04/areas-in-aspnetmvc.aspx
James S