I am wondering how can I define a routing map like this:
{TreePath}/{Action}{Id}
TreeMap is dynamically loaded from a database like this:
'Gallery/GalleryA/SubGalleryA/View/3'
See Question&Answers more detail:osI am wondering how can I define a routing map like this:
{TreePath}/{Action}{Id}
TreeMap is dynamically loaded from a database like this:
'Gallery/GalleryA/SubGalleryA/View/3'
See Question&Answers more detail:osYou can create a custom route handler to do this. The actual route is a catch-all:
routes.MapRoute(
"Tree",
"Tree/{*path}",
new { controller = "Tree", action = "Index" })
.RouteHandler = new TreeRouteHandler();
The tree handler looks at path, extracts the last part as action, and then redirects to the controller. The action part is also removed from path. Adding the {id} part should be straightforward.
public class TreeRouteHandler : IRouteHandler
{
public IHttpHandler GetHttpHandler(RequestContext requestContext)
{
string path = requestContext.RouteData.Values["path"] as string;
if (path != null)
{
int idx = path.LastIndexOf('/');
if (idx >= 0)
{
string actionName = path.Substring(idx+1);
if (actionName.Length > 0)
{
requestContext.RouteData.Values["action"] = actionName;
requestContext.RouteData.Values["path"] =
path.Substring(0, idx);
}
}
}
return new MvcHandler(requestContext);
}
}
Your controller then works as you would expect it:
public class TreeController : Controller
{
public ActionResult DoStuff(string path)
{
ViewData["path"] = path;
return View("Index");
}
}
Now you can call URL like /Tree/Node1/Node2/Node3/DoStuff
. The path that the action gets is Node1/Node2/Node3